package com.zhixun.mobile.modules.member.web;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.boxin.framework.base.utils.Constants;
import com.boxin.framework.base.utils.DateUtils;
import com.boxin.ims.modules.momarketing.common.QRCodeUtils;
import com.boxin.ims.modules.momarketing.entity.CouponConfig;
import com.boxin.ims.modules.momarketing.entity.CustomPage;
import com.boxin.ims.modules.momarketing.entity.PageVisit;
import com.boxin.ims.modules.momarketing.entity.QRCode;
import com.boxin.ims.modules.momarketing.service.CouponConfigService;
import com.boxin.ims.modules.momarketing.service.CustomPageService;
import com.boxin.ims.modules.momarketing.service.QRCodeService;
import com.boxin.ims.modules.recharge.entity.Recharge;
import com.boxin.ims.modules.recharge.service.RechargeCacheService;
import com.boxin.ims.modules.recharge.service.RechargeService;
import com.boxin.ims.modules.wechat.busi.LotteryProcessor;
import com.boxin.ims.modules.wechat.busi.ProcessMessage;
import com.boxin.ims.modules.wechat.entity.Lottery;
import com.boxin.ims.modules.wechat.entity.LotteryConfig;
import com.boxin.ims.modules.wechat.entity.LotteryLog;
import com.boxin.ims.modules.wechat.entity.LotteryRecord;
import com.boxin.ims.modules.wechat.entity.Message;
import com.boxin.ims.modules.wechat.entity.NewsReply;
import com.boxin.ims.modules.wechat.entity.ReturnResult;
import com.boxin.ims.modules.wechat.entity.Seckill;
import com.boxin.ims.modules.wechat.entity.SeckillConfig;
import com.boxin.ims.modules.wechat.entity.SeckillGainer;
import com.boxin.ims.modules.wechat.entity.SignupConfig;
import com.boxin.ims.modules.wechat.entity.UserDefine;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.entity.tmessage.BusinessMessageTemplate;
import com.boxin.ims.modules.wechat.entity.tmessage.UserMessageTemplate;
import com.boxin.ims.modules.wechat.score.entity.ExchangeRecord;
import com.boxin.ims.modules.wechat.score.entity.ScoreExchange;
import com.boxin.ims.modules.wechat.score.service.ExchangeRecordService;
import com.boxin.ims.modules.wechat.score.service.ScoreExchangeService;
import com.boxin.ims.modules.wechat.service.LotteryConfigService;
import com.boxin.ims.modules.wechat.service.LotteryLogService;
import com.boxin.ims.modules.wechat.service.LotteryRecordService;
import com.boxin.ims.modules.wechat.service.LotteryService;
import com.boxin.ims.modules.wechat.service.MemberScoreService;
import com.boxin.ims.modules.wechat.service.SeckillService;
import com.boxin.ims.modules.wechat.service.SignupConfigService;
import com.boxin.ims.modules.wechat.service.UserDefineService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.service.tmessage.UserMessageTemplateService;
import com.boxin.ims.modules.wechat.tmessage.TemplateMessage;
import com.boxin.ims.modules.wechat.tmessage.TemplateMessageFactory;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.boxin.ims.modules.wechat.utils.SpringUtils;
import com.boxin.ims.modules.wechat.utils.TemplateMessageUtils;
import com.boxin.ims.modules.wechat.utils.TokenUtils;
import com.boxin.ims.modules.wechat.utils.WechatInterfaceUtils;
import com.boxin.ims.modules.wechat.utils.WechatUtils;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.zhixun.mobile.common.utils.EncryptUtils;
import com.zhixun.mobile.common.utils.StringUtils;
import com.zhixun.mobile.extend.utils.PageVisitExtendUtils;
import com.zhixun.mobile.extend.utils.SeckillExtendUtils;
import com.zhixun.mobile.modules.base.web.BaseController;
import com.zhixun.mobile.modules.member.service.MemberService;
import com.zhixun.mobile.sys.utils.AssertUtils;
import com.zhixun.mobile.sys.utils.MemberUtils;
import com.zhixun.mobile.sys.utils.SessionMemberUtils;
import com.thinkgem.jeesite.common.config.Global;

@Controller
@RequestMapping(value = Global.FRONT_PATH+"/member")
public class IndexController extends BaseController {

	@PersistenceContext
	private EntityManager entityManager;
	
	@Autowired
	SignupConfigService signupConfigService;
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	UserMessageTemplateService userMessageTemplateService;

	@Autowired
	WechatDaoHelper wechatDaoHelper;

	@Autowired
	MemberService memberService;

	@Autowired
	WechatMemberService wechatMemberService;
	
	@Autowired
	private ExchangeRecordService exchangeRecordService;
	
	@Autowired
	private WeChatService weChatService;
	
	@Autowired
	private UserDefineService userDefineService;
	
	
	@Autowired
	private SeckillService seckillService;

	@Autowired
	private LotteryRecordService lotteryRecordService;

	@Autowired
	private ScoreExchangeService scoreExchangeService;
	@Autowired
	private CouponConfigService couponConfigService;

	@Autowired
	private LotteryProcessor lotteryProcessor;

	@Autowired
	private LotteryConfigService lotteryConfigService;

	@Autowired
	private LotteryLogService lotteryLogService;

	@Autowired
	private LotteryService lotteryService;

	@Autowired
	private RechargeService rechargeService;

	@Autowired
	private QRCodeService qrCodeService;

	@Autowired
	private RechargeCacheService rechargeCacheService;

	private Logger logger = Logger.getLogger(IndexController.class);

	@RequestMapping(value = { "index", "" })
	public String index(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		System.out.println("index....:");
		return tologin(request, response, model);
	}

	/**
	 * @author Jakemanse
	 * @time 2014-2-26 4:15:46
	 * @function <p>
	 * 
	 *           </p>
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 * @throws NumberFormatException
	 */
	@RequestMapping(value = "login")// TODO 会员登录
	public String login(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes)
			throws NumberFormatException, IOException, ParseException {

		String style = request.getParameter("style");


		String uid = request.getParameter("uid");
		style = this.isStyle(new User(Long.valueOf(uid)));
		String pwd = request.getParameter("pwd");
		String wechatId = request.getParameter("wechatId");
		String mobile = request.getParameter("mobile");
		String topage = request.getParameter("topage");
		String page = "";

		if (StringUtils.isEmpty(uid) || StringUtils.isEmpty(wechatId)
				|| StringUtils.isEmpty(mobile)) {
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

		request.setAttribute("topage", topage);
		request.setAttribute("wechatId", wechatId);
		request.setAttribute("uid", uid);
		request.setAttribute("style", style);

		// 判断是否已经登录
		WechatMember member = null;
		member = SessionMemberUtils.getSessionMemberByUserId(request, uid);
		boolean login = false;
		if (AssertUtils.notNull(member)) {
			login = true;
		}
		if (member == null) {
			User user = new User();
			user.setId(Long.parseLong(uid));
			member = wechatMemberService.getByWechatMemberId(user, wechatId);
			WechatMember wechatMember = wechatMemberService.getByMobile(user,
					mobile);
			if (member != null && wechatMember != null) {
				if (member.getMobile().equals(wechatMember.getMobile())) {
					login = EncryptUtils.validatePassword(pwd,
							member.getPassword());
				}
				// /登录
				if (login) {
					SessionMemberUtils.addSessionValue(request,
							"member_" + uid, member);
				}
			} else {
				login = false;
			}
		}
		model.addAttribute("wechatMember", member);

		if (login) {
			// TODO 跳转成功后可以通过topage调回原来的
			request.setAttribute("wechatMember", member);

			if (member.isRandomPassword()) {

				model.addAttribute("message",
						MemberUtils.FIRSTLOGINUPDATEPASSWORD);

				return this.toupdatePwd(request, response, model,
						redirectAttributes);
			} else {
				if (AssertUtils.notNullOrEmpty(topage)) {

					page = this.tofangfa(Long.parseLong(uid), model, request,
							response, topage, style, redirectAttributes);

					return page;
				} else {
					return "modules/member/themes/" + style + "/memberCenter";
				}
			}
			
		}

		Map<String, Object> map = this.beforeLogin(uid, wechatId);

		model.addAttribute("login_mobile", map.get("mobile"));
		model.addAttribute("pwd", map.get("pwd"));
		model.addAttribute("errormessage", "您的手机号或密码不正确!");
		model.addAttribute("reg", "reg");
		return "modules/member/themes/" + style + "/reg";
	}

	@RequestMapping(value = "tologin") // TODO 跳转登陆
	public String tologin(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String style = request.getParameter("style");

		String topage = request.getParameter("topage");
		String id = request.getParameter("uid");
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId");
		model.addAttribute("uid", id);
		request.setAttribute("topage", topage);
		model.addAttribute("wechatId", wechatId);
		request.setAttribute("style", style);
		System.out.println("返回登录页面......");

		Map<String, Object> map = this.beforeLogin(id, wechatId);

		model.addAttribute("login_mobile", map.get("mobile"));
		model.addAttribute("pwd", map.get("pwd"));
		model.addAttribute("reg", "reg");
		return "modules/member/themes/" + style + "/reg";
	}

	@RequestMapping(value = "reg") // TODO 跳转注册
	public String register(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		String style = request.getParameter("style");


		String uid = request.getParameter("uid");
		style = this.isStyle(new User(Long.valueOf(uid)));
		String topage = request.getParameter("topage");
		String wechatId = request.getParameter("wechatId");

		model.addAttribute("reg", "reg");
		model.addAttribute("uid", uid);
		model.addAttribute("topage", "reg");
		model.addAttribute("wechatId", wechatId);
		request.setAttribute("style", style);
		
		return "modules/member/themes/" + style + "/reg";
	}

	// -------------会员绑定----------------------------------------------------------------------------
	/**
	 * @author songyan
	 * @time 2014-2-28
	 */
	@RequestMapping(value = "bind") // TODO 会员绑定
	public String bind(Long uid, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		String style = request.getParameter("style");


		User user = new User();
		user.setId(uid);
		String message = "";

		String topage = request.getParameter("topage");
		String wechatId = request.getParameter("wechatId");
		String mobile = request.getParameter("mobile");
		String id = request.getParameter("uid");
		
		style = this.isStyle(new User(Long.valueOf(id)));
		
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);

		model.addAttribute("topage", topage);

		if (StringUtils.isEmpty(wechatId) || StringUtils.isEmpty(id)) {
			message = "对不起,你的请求发生错误，请返回微信中回复【会员申请】或【会员中心】重新注册，谢谢！";
			model.addAttribute("message", message);
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}
		
		UserDefine userDefine = WechatUtils
				.getUserDefineByUserId(user.getId());
		
		request.setAttribute("userDefine", userDefine);

		WechatMember wechatMember = wechatMemberService.getByWechatMemberId(
				user, wechatId);
		

		if (wechatMember != null) { // 已经绑定过的会员

			WechatMember wechatMember2 = isLogin(request, "" + uid);

			if (wechatMember2 != null) {

				request.setAttribute("wechatMember", wechatMember);
				
				return "modules/member/themes/" + style + "/memberCenter";
			} else {

				Map<String, Object> map = this.beforeLogin(id, wechatId);

				model.addAttribute("login_mobile", map.get("mobile"));
				model.addAttribute("pwd", map.get("pwd"));
				
				model.addAttribute("reg", "reg");
				return "modules/member/themes/" + style + "/reg";
			}

		}

		
		
		if ("reg".equals(request.getParameter("action"))) { // 保存绑定
			String name = request.getParameter("name");

			String recommendCode = request.getParameter("recommendCode"); // 推荐码

			WechatMember mobileMember = wechatMemberService.getByMobile(user,
					mobile);
			if (wechatMember == null && mobileMember == null) { // 还未绑定
				wechatMember = new WechatMember();
				wechatMember.setUser(user);
				wechatMember.setWechatId(wechatId);
				wechatMember.setScore(0);
				wechatMember.setActiveScore(0);
				wechatMember.setConsumeScore(0);
				wechatMember.setCreditScore(0);
				wechatMember.setName(name);
				// wechatMember.setBirthday(birthday);
				wechatMember.setSex("保密");
				wechatMember.setMobile(mobile);
				// wechatMember
				// .setPassword(EncryptUtils.MD5EncodeString(password));
				wechatMember.setLastSignTime(null);
				wechatMember.setIsRandomPassword(false);

				Boolean advanceInterface = memberService.selectInterfaceFlagByuserID(uid);	//是否开通了高级接口

				if (advanceInterface) {
					try {
						WechatMember member = memberService.operateInterface(
								uid, wechatId);
						wechatMember.setCity(member.getCity());
						wechatMember.setCountry(member.getCountry());
						wechatMember.setHeadimgurl(member.getHeadimgurl());
						wechatMember.setLanguage(member.getLanguage());
						wechatMember.setNickname(member.getNickname());
						wechatMember.setProvince(member.getProvince());
						// wechatMember.setSex(member.getSex());
						wechatMember
								.setSubscribeTime(member.getSubscribeTime());
						wechatMember.setAge(member.getAge());
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
				
				
				
				
				/****************************增加推荐处理 开始****************************************/
				
				
				//注册会员加积分
				if(userDefine.getRegisterScore() != null  &&  userDefine.getRegisterScore() >0){
					//wechatMember.setScore(userDefine.getRegisterScore());
					ScoreUtils.addScore(wechatMember, userDefine.getRegisterScore(),"0","注册会员送"+userDefine.getRegisterScore()/1000d+"个活动积分");
				}
				
				
				boolean isRecommandMoney = false;
				//注册会员送奖金
				if(UserDefine.YES.equals(userDefine.getRecommendMoneyFlag())){		//必须是推荐的会员注册才送奖金
					isRecommandMoney = true;
				}else{
					if(	userDefine.getRegisterMoney()!= null  &&  userDefine.getRegisterMoney() >0){
						//wechatMember.setMoney(userDefine.getRecommendMoney());
						ScoreUtils.addMoney(wechatMember, userDefine.getRegisterMoney(), "注册会员送奖金");
					}
				}
				
				
				
				
				
				//推荐码不为空
				if(StringUtils.isNotEmpty(recommendCode)){
					
					WechatMember parentMember =  wechatMemberService.getByRecommandCode(recommendCode);
					boolean recommendLotteryFlag = false;
					if(parentMember!=null){
						wechatMember.setParentCode(recommendCode);
						wechatMemberService.save(wechatMember);			//update the parent recommend code
						
						int repeatCount = userDefine.getRecommendLotteryRepeatCount();
						//
						LotteryRecord queryRecord = new LotteryRecord();
						queryRecord.setUser(user);
						queryRecord.setMember(parentMember);
						queryRecord.setSourceType(LotteryRecord.SURCE_TYPE_RECOMMEND);
						
						int mylotteryCount = lotteryRecordService.findLotteryRecordCount(queryRecord);
						
						
						//要求至少的子会员数
						int requireSubCount = userDefine.getRequireSubMemberCount();
						boolean subMemberFlag = false;
						
						if(requireSubCount >0){
							List<WechatMember>  memberList = wechatMemberService.findMyRecommandMembers(recommendCode);
							if(memberList!=null){
								int mCnt = memberList.size();
								if(mCnt>=requireSubCount){
									subMemberFlag = true;
								}else{
									logger.debug("推荐码为:【"+recommendCode+"】的会员下有"+mCnt+"个会员，要求至少有"+requireSubCount+"会员才能送礼品:"+userDefine.getRecommendLotteryName());
								}
							}else{
								logger.debug("推荐码为:【"+recommendCode+"】的会员下有0个会员，要求至少有"+requireSubCount+"个会员才能送礼品:"+userDefine.getRecommendLotteryName());
							}
						}else{
							subMemberFlag = true;
						}
						
						
						//推荐的会员，送奖金
						if(isRecommandMoney){
							if(	userDefine.getRegisterMoney()!= null  &&  userDefine.getRegisterMoney() >0){
								//wechatMember.setMoney(userDefine.getRecommendMoney());
								ScoreUtils.addMoney(wechatMember, userDefine.getRegisterMoney(), "注册会员送奖金");
							}
						}
						
						//是否可以再获得奖品
						if(mylotteryCount<repeatCount   && subMemberFlag){
							
							//推荐人获得奖品  仅限一次
							if(UserDefine.YES.equals(userDefine.getRecommendLottery())){
								String lname = userDefine.getRecommendLotteryName();
								String ldesc = userDefine.getRecommendLotteryDesc();
								String ltitle = userDefine.getRecommendLotteryTitle();
								
								LotteryRecord lRecord = new LotteryRecord();
								lRecord.setMember(parentMember);
								lRecord.setSourceType(LotteryRecord.SURCE_TYPE_RECOMMEND);
								lRecord.setName(userDefine.getRecommendLotteryName());
								lRecord.setStatus(LotteryRecord.STATUS_NORMAL);
								lRecord.setUser(user);
								lRecord.setEndTime(DateUtils.getDelayDate(userDefine.getRecommendLotteryValidDays()));
								lRecord.setRemarks("推荐子会员【"+wechatMember.getName()+"】送礼品.");
								lotteryRecordService.save(lRecord);
								
								//recommendLotteryFlag = true;		//已送礼品
								
								
								
								//发送及时消息
								try {
									String picUrl =QRCodeUtils.getQRCodePNGURL(lRecord.getQrCode().getId());
									String url =QRCodeUtils.getQRCodePNGPageURL(lRecord.getQrCode().getId())+"&uid="+user.getId();
									WechatInterfaceUtils.sendMsgToMember(user.getId(), parentMember, ltitle, ldesc, picUrl, url);
								} catch (Exception e) {
									e.printStackTrace();
									logger.error("给会员 【"+parentMember.getName()+"】发送及时消息失败.");
								}
							}
						}
						
						//如果已送礼品则不送积分
						//不限定了
						if(!recommendLotteryFlag){
							
							//推荐送积分
							if((userDefine.getRecommendScore()!=null  && userDefine.getRecommendScore() >0)   && !recommendLotteryFlag){
								
								if(parentMember !=  null){
									ScoreUtils.addScore(parentMember, userDefine.getRecommendScore(),"0","推荐会员送"+userDefine.getRecommendScore()/1000d+"活动积分");
									//ScoreUtils.addScore(wechatMember, userDefine.getRecommendScore(), "被推荐会员送积分");
									
									//发送及时消息
									try {
										String picUrl = "http://weixin.zhaotang.net/zt/f/userfiles/images/"+userDefine.getRecommendLotteryPic();
										String url = "";
										String desc = "恭喜您已成功推荐 【"+wechatMember.getName()+"】成为我们的会员,感谢您的支持,本次奖励您"+((double)userDefine.getRecommendScore()/1000)+"个积分.";
										WechatInterfaceUtils.sendMsgToMember(user.getId(), parentMember, "推荐会员送积分", desc, picUrl, url);
									} catch (Exception e) {
										e.printStackTrace();
										logger.error("给会员 【"+parentMember.getName()+"】发送及时消息失败.");
									}
									
								}
							}


							//推荐送奖金
							if((userDefine.getRecommendMoney()!=null  && userDefine.getRecommendMoney() >0 )  && !recommendLotteryFlag ){
								if(parentMember ==  null)	parentMember = wechatMemberService.getByRecommandCode(recommendCode);
								if(parentMember !=  null){
									
									
									//送奖品 和 日志
									ScoreUtils.addMoney(parentMember, userDefine.getRecommendMoney(), "推荐会员送奖金");
									//ScoreUtils.addScore(wechatMember, userDefine.getRecommendMoney(), "被推荐会员送奖金");
									
//									int resultMoney = wechatMember.getMoney() + userDefine.getRecommendMoney();
//									wechatMember.setMoney((resultMoney<0)?0:resultMoney);
//									wechatMemberService.save(wechatMember);
									
									
									//父会员的奖金 池
									String pname = parentMember.getName();
									Long puID = parentMember.getUser().getId();
									Integer pmoney = userDefine.getRecommendMoney();
									Integer pscore = userDefine.getRecommendScore();
									Long pparentMemberId = parentMember.getId();
									Long pchildMemberId = wechatMember.getId();

									rechargeCacheService
											.saveRechargeCache(pname, puID, pmoney, pscore,
													pparentMemberId, pchildMemberId);
									
									//发送及时消息
									try {
										String picUrl = "";
										String url = "";
										String desc = "恭喜您已成功推荐 ["+wechatMember.getName()+"]成为我们的会员,感谢您的支持,本次奖励您"+((double)userDefine.getRecommendMoney()/100)+"元 .";
										WechatInterfaceUtils.sendMsgToMember(user.getId(), parentMember, "推荐会员送奖金", desc, picUrl, url);
									} catch (Exception e) {
										e.printStackTrace();
										logger.error("给会员 【"+parentMember.getName()+"】发送及时消息失败.");
									}
									
								}
							}
							
							
							//双向送积分或奖金  即 推荐获得积分的基础上还 增加 注册会员的积分或奖金
							if(UserDefine.ADD_TYPE_DOUBLE.equals(userDefine.getAddType())){			//双向增加
								
								//注册会员加积分
								if(userDefine.getRegisterScore() != null  &&  userDefine.getRegisterScore() >0){
									//wechatMember.setScore(userDefine.getRegisterScore());
									ScoreUtils.addScore(wechatMember, userDefine.getRegisterScore(),"0","注册会员送"+userDefine.getRegisterScore()/1000d+"个活动积分");
								}
								
								//注册会员送奖金
								if(userDefine.getRegisterMoney()!= null  &&  userDefine.getRegisterMoney() >0){
									//wechatMember.setMoney(userDefine.getRecommendMoney());
									//ScoreUtils.addScore(wechatMember, userDefine.getRegisterMoney(), "注册会员送奖金");
									
									int resultMoney = wechatMember.getMoney() + userDefine.getRegisterMoney();
									wechatMember.setMoney((resultMoney<0)?0:resultMoney);
									wechatMemberService.save(wechatMember);
								}
							}
						}
						
							
						}
						
						
				} 
				
				
				
				/****************************增加积分/金额结束***************************************/
				

				if(wechatMember.getId()==null || wechatMember.getId() <= 0)	  wechatMemberService.save(wechatMember);
				// 生成推荐码  暗号
				wechatMember
						.setRecommendCode(""
								+ StringUtils.leftPad(
										"" + wechatMember.getId(), 6, "0"));// 推荐码

				//生成会员卡号
				wechatMember.setNumber("MBR"
						+ StringUtils.leftPad("" + wechatMember.getId(), 10,
								"0")); // 会员卡号

				wechatMemberService.save(wechatMember);
				// 把会员表推荐码字段置成会员ID 推荐码=会员ID
				// 生成会员卡
				generateMemberCard(wechatMember, request);

				
				
				message = "亲，恭喜您成为我们的微会员!请设置您的密码";
				// 是 否注册会员有礼
				if ("1".equals(userDefine.getRegLottery())) { // 注册会员有奖
					// TODO 生成注册奖品
					LotteryRecord lotteryRecord = new LotteryRecord();
					lotteryRecord.setSourceType(LotteryRecord.SURCE_TYPE_REG);
					lotteryRecord.setName(userDefine.getLotteryName());
					lotteryRecord.setStartTime(new Date());

					lotteryRecord
							.setEndTime(com.boxin.framework.base.utils.DateUtils
									.getDelayDate(userDefine
											.getLotteryValidDays()));
					lotteryRecord.setMember(wechatMember);
					lotteryRecord.setStatus(LotteryRecord.STATUS_NORMAL);
					lotteryRecord.setUser(user);

					lotteryRecordService.save(lotteryRecord);
					model.addAttribute("regLottery", "恭喜您获得了本次注册会员送礼活动的【"
							+ userDefine.getLotteryName()
							+ "】,请返回微信点击【我的礼品】菜单获取电子凭证,并到附近实体店兑换礼品!");
				}

				model.addAttribute("message", message);
				model.addAttribute("info",
						"您现在可以参与:<p>签到送积分</p><p></p><p>在线秒杀</p>在线抽奖<p>...</p>");
				model.addAttribute("userName", name);

				model.addAttribute("login_mobile", mobile);
				
				WechatMember member= isLogin(request, ""+uid);
				
				model.addAttribute("wechatMember", member);
				
				return "modules/member/themes/" + style + "/memberCenter";
			} else {

				if (wechatMember != null
						&& wechatMember.getMobile().equals(mobile)) {
					message = "亲,您早已是我们的会员了,";
				} else {
					message = "您输入的手机号[" + mobile + "]已经与其它微信绑定，请确定是否输入错误!";
				}

				if (mobileMember != null) {
					message = "您输入的手机号[" + mobile + "]已经与其它微信绑定，请确定是否输入错误!";
				}

				//
				model.addAttribute("message", message);
				
				model.addAttribute("reg", "reg");
				return "modules/member/themes/" + style + "/reg";
			}

		} else { // 导航到指定页

			model.addAttribute("reg", "reg");
		}

		model.addAttribute("message", message);
		
		model.addAttribute("reg", "reg");
		return "modules/member/themes/" + style + "/reg";
	}

	/**
	 * @author Jakemanse
	 * @time 2014-4-3 下午2:19:47
	 * @function <p>
	 *           生成会员卡 及会员卡二维码
	 *           </p>
	 * @param member
	 * @param request
	 */
	// TODO 生成会员卡 及会员卡二维码
	private void generateMemberCard(WechatMember member,
			HttpServletRequest request) {
		Recharge recharge = rechargeService.getRechargeByMemberId(member
				.getId());

		if (recharge == null) {
			recharge = new Recharge();
			recharge.setMember(member);
			recharge.setMoney(0);
			recharge.setName(member.getName());
			recharge.setNumber(member.getNumber());
			recharge.setType(Recharge.CARD_TYPE_GENERAL);
			recharge.setUser(member.getUser());

			rechargeService.save(recharge);
		}

		if (recharge != null) {

			if (recharge.getQrCode() == null
					|| recharge.getQrCode().getId() <= 0) { // 生成二维码
				QRCode qrcode = new QRCode();
				String content = recharge.getMember().getNumber();
				qrcode.setContent(content);
				String path = Constants.getDefaultQRCodeResourcePath();
				path = WechatUtils.getMemberCardResourceSavePath(request);
				FileUtils.createDirectory(path);
				String filePath = path + File.separator + content;

				QRCodeUtils.generateNoMarginQRCodePNG(content, filePath, 300,
						300);
				qrcode.setFileName(content + ".png");
				qrcode.setPngPath(filePath + ".png");
				qrCodeService.save(qrcode);

				recharge.setQrCode(qrcode);

				rechargeService.save(recharge);
			}
		}
	}

	// -------------会员绑定----------------------------------------------------------------------------
	// -------------在线签到----------------------------------------------------------------------------

	/**
	 * @author songyan
	 * @time 2014-3-3 11:11
	 * @function <p>
	 *           导航到网页签到
	 *           </p>
	 * @param uid
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	//TODO 在线签到
	@RequestMapping(value = "tosignup")
	public String toSignup(Model model, HttpServletRequest request,
			HttpServletResponse response) {

		String style = request.getParameter("style");


		String wechatId = request.getParameter("wechatId");

		String uid = request.getParameter("uid");
		
		style = this.isStyle(new User(Long.valueOf(uid)));
		
		model.addAttribute("uid", uid);
		model.addAttribute("wechatId", wechatId);
		request.setAttribute("style", style);

		model.addAttribute("topage", "tosignup");

		WechatMember wechatMember = this.isLogin(request, "" + uid);

		if (AssertUtils.notNull(wechatMember)) {

			return "modules/member/themes/" + style + "/toSignup";
		} else {

			Map<String, Object> map = this.beforeLogin(uid, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	/**
	 * @author songyan
	 * @time 2014-3-3 11:11
	 * @function <p>
	 *           签到处理
	 *           </p>
	 * @param uid
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	//TODO 签到处理
	@RequestMapping(value = "signup")
	public String signup(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		String style = request.getParameter("style");


		String wechatId = request.getParameter("wid");
		String pwd = request.getParameter("pwd");
		String uid = request.getParameter("uid");
		
		style = this.isStyle(new User(Long.valueOf(uid)));
		
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", uid);
		request.setAttribute("style", style);
		model.addAttribute("topage", "tosignup");

		User user = new User();
		user.setId(Long.parseLong(uid));
		WechatMember member = wechatMemberService.getByWechatMemberId(user,
				wechatId);
		String message = "";
		if (member != null) {

			UserDefine userDefine = WechatUtils.getUserDefineByUserId(user
					.getId()); // 定义
			String upcon = "签到";

			SignupConfig signupConfig = signupConfigService.getByUserId(member
					.getUser().getId());

			if (DateUtils.getTodayString().equals(member.getLastSignTime())) { // 未签到+签到成功

				// 当签到过后显示给用户今日签到的分数
				Integer todayScore = 0;
				if (signupConfig != null && signupConfig.getStartup()) {
					todayScore = signupConfigService.getTodayScore(userDefine,
							member, signupConfig);// 计算今天签到应该得到多少分
				} else {
					todayScore = userDefine.getSignScore();
				}

				Integer score = member.getScore();
				score = (score == null) ? 0 : score;
				message = WechatUtils.processUserBusinessReply(user.getId(),
						upcon, score);
				if (com.thinkgem.jeesite.common.utils.StringUtils
						.isEmpty(message)) {
					message = "今天您已签到过了,您当前的积分为:" + score/1000 + "分!";
				} else {
					message = message.replaceAll("%分值%", todayScore/1000 + "");
					message = message.replaceAll("%积分%", score/1000 + "");
					message = message.replaceAll("%连续签到%",
							member.getSignupCount() + "");
					message = "今天您已签到过了," + message;
				}
			} else {

				if (signupConfig != null && signupConfig.getStartup()) {
					signupConfigService.isSignup(signupConfig, member);// 记录连续签到的天数
					// 签到成功
					Integer score = member.getActiveScore();
					member.setUpdateTime(new Date());

					member.setLastSignTime(DateUtils.getTodayString());

					Integer todayScore = signupConfigService.getTodayScore(
							userDefine, member, signupConfig);// 计算今天签到应该得到多少分

					score += todayScore;
					member.setActiveScore(score);
					member.setScore(member.getScore()+todayScore);
					wechatMemberService.save(member);

					message = WechatUtils.processUserBusinessReply(
							user.getId(), upcon, score);
					if (com.thinkgem.jeesite.common.utils.StringUtils
							.isEmpty(message)) {
						message = "签到成功,您当前积分为:" + member.getScore()/1000 + "分!";
					} else {
						message = message.replaceAll("%分值%", todayScore/1000 + "");
						message = message.replaceAll("%积分%", member.getScore()/1000 + "");
						message = message.replaceAll("%连续签到%",
								member.getSignupCount() + "");
					}
					// 记录签到
					ScoreUtils.addWechatMemberSignScore(member,
							todayScore);

				} else {
					Integer activeScore = member.getActiveScore();
					activeScore = (activeScore == null) ? 1 : activeScore
							+ userDefine.getSignScore();
					member.setActiveScore(activeScore);
					member.setUpdateTime(new Date());
					member.setLastSignTime(DateUtils.getTodayString());
					wechatMemberService.save(member);

					message = WechatUtils.processUserBusinessReply(
							user.getId(), upcon, activeScore);
					if (com.thinkgem.jeesite.common.utils.StringUtils
							.isEmpty(message)) {
						message = "签到成功,您当前的活动积分为:" + activeScore/1000 + "分!";
					} else {
						message = message.replaceAll("%分值%",
								userDefine.getSignScore()/1000 + "");
						message = message.replaceAll("%活动积分%", activeScore/1000 + "");
					}
					// 记录签到
					ScoreUtils.addWechatMemberSignScore(member,
							userDefine.getSignScore());
				}
			}

		} else {
			// 还不是会员
			message = "您还不是我们的会员请先注册会员，请签到吧！";
			model.addAttribute("message", message);

			return bind(Long.parseLong(uid), model, request, response);

		}

		model.addAttribute("message", message);

		return "modules/member/themes/" + style + "/signupOk";
	}

	// -------------在线签到----------------------------------------------------------------------------
	// -------------积分兑换----------------------------------------------------------------------------
	/**
	 * @author songyan
	 * @time 2014-3-3 14:04
	 * @function <p>
	 *           商品积分页面
	 *           </p>
	 * @param id
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	//TODO 积分兑换
	@RequestMapping(value = "toexchange")
	public String toExchangeScore(Model model, HttpServletRequest request,
			HttpServletResponse response) {

		String style = request.getParameter("style");


		String wechatId = request.getParameter("wechatId"); // OpenId
		String id = request.getParameter("uid");
		
		style = this.isStyle(new User(Long.valueOf(id)));
		
		User user = new User();
		user.setId(Long.parseLong(id));

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);

		model.addAttribute("topage", "toExchangeScore");

		// 需要判断是否已经登录过
		WechatMember member = this.isLogin(request, "" + id);
		if (member == null) { // 没有登录先进入登录页面
			if ("34".equals(id)) { // 阳光麦康处理
				member = wechatMemberService
						.getByWechatMemberId(user, wechatId);
				//
			} else {
				request.setAttribute("topage", "toexchange");
				// return "redirect:" + Global.FRONT_PATH+ "/wechat/login/"+id;

				Map<String, Object> map = this.beforeLogin(id, wechatId);

				model.addAttribute("login_mobile", map.get("mobile"));
				model.addAttribute("pwd", map.get("pwd"));
				
				model.addAttribute("reg", "reg");
				return "modules/member/themes/" + style + "/reg";

			}
		}

		// 兑换的列表
		List<ScoreExchange> scoreExchangeList = scoreExchangeService
				.findAllByUserId(Long.parseLong(id));
		model.addAttribute("scoreExchangeList", scoreExchangeList);

		request.setAttribute("wechatMember", member);

		return "modules/member/themes/" + style + "/exchangeScore";
	}
	
	
	
	/**
	 * @author songyan
	 * @time 2014-3-3 14:04
	 * @function <p>
	 *           商品积分页面
	 *           </p>
	 * @param id
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	//TODO 积分兑换
	@RequestMapping(value = "toexchangeScoreListByShopping")
	public String toExchangeScoreByShopping(Model model, HttpServletRequest request,
			HttpServletResponse response) {

		String style = request.getParameter("style");


		String wechatId = request.getParameter("wechatId"); // OpenId
		String id = request.getParameter("uid");
		
		style = this.isStyle(new User(Long.valueOf(id)));
		
		User user = new User();
		user.setId(Long.parseLong(id));

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);

		model.addAttribute("topage", "toExchangeScore");

		// 需要判断是否已经登录过
		WechatMember member = this.isLogin(request, "" + id);
		if (member == null) { // 没有登录先进入登录页面
			if ("34".equals(id)) { // 阳光麦康处理
				member = wechatMemberService
						.getByWechatMemberId(user, wechatId);
				//
			} else {
				request.setAttribute("topage", "toexchange");
				// return "redirect:" + Global.FRONT_PATH+ "/wechat/login/"+id;

				Map<String, Object> map = this.beforeLogin(id, wechatId);

				model.addAttribute("login_mobile", map.get("mobile"));
				model.addAttribute("pwd", map.get("pwd"));
				
				model.addAttribute("reg", "reg");
				return "modules/member/themes/" + style + "/reg";

			}
		}

		// 兑换的列表
		List<ScoreExchange> scoreExchangeList = scoreExchangeService
				.findAllByUserId(Long.parseLong(id));
		
		List<ScoreExchange> userList =  scoreExchangeService.findUserList();
		
		
		//对多用户下兑换列表进行处理
		
		List< List<ScoreExchange>> map = new ArrayList< List<ScoreExchange>>();
		for (int i = 0; i < userList.size(); i++) {
			 List<ScoreExchange> temp = new  ArrayList<ScoreExchange>();
			 for (int j = 0; j <scoreExchangeList.size(); j++) {
				if(userList.get(i).getUser().getId()==scoreExchangeList.get(j).getUser().getId()){
					temp.add(scoreExchangeList.get(j));
				}
			}
			 if(temp.size()!=0){
				 map.add(temp);
			 }
		}
		
		
		model.addAttribute("scoreExchangeList", scoreExchangeList);
		
		model.addAttribute("map", map);

		request.setAttribute("wechatMember", member);

		return "modules/member/themes/fashion/exchangeScoreListByShopping";
	}
	
	
	@RequestMapping(value = "toexchangeByShopping")
	public String toexchangeScoreByShopping(Model model, HttpServletRequest request,
			HttpServletResponse response) {

		String style = request.getParameter("style");


		String wechatId = request.getParameter("wechatId"); // OpenId
		String id = request.getParameter("uid");
		String userId=request.getParameter("userId");
		
		style = this.isStyle(new User(Long.valueOf(id)));
		
		User user = new User();
		user.setId(Long.parseLong(id));

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);

		model.addAttribute("topage", "toExchangeScore");

		// 需要判断是否已经登录过
		WechatMember member = this.isLogin(request, "" + id);
		if (member == null) { // 没有登录先进入登录页面
			if ("34".equals(id)) { // 阳光麦康处理
				member = wechatMemberService.getByWechatMemberId(user, wechatId);
				//
			} else {
				request.setAttribute("topage", "toexchange");
				// return "redirect:" + Global.FRONT_PATH+ "/wechat/login/"+id;

				Map<String, Object> map = this.beforeLogin(id, wechatId);

				model.addAttribute("login_mobile", map.get("mobile"));
				model.addAttribute("pwd", map.get("pwd"));
				
				model.addAttribute("reg", "reg");
				return "modules/member/themes/" + style + "/reg";

			}
		}

		// 兑换的列表
		List<ScoreExchange> scoreExchangeList = scoreExchangeService.findAllByUserId(Long.parseLong(userId));
		model.addAttribute("scoreExchangeList", scoreExchangeList);
		
		User pUser=systemService.getUser(Long.parseLong(userId));

		request.setAttribute("wechatMember", member);
		request.setAttribute("pUser", pUser);

		return "modules/member/themes/" + style + "/exchangeScoreByShopping";
	}
	
	

	/**
	 * 跳到积分兑换的商品页
	 * 
	 * @author xiaoqian
	 * @param id
	 * @param model
	 * @param request
	 * @param response
	 * @return 2014-3-6下午3:39:55
	 */
	//TODO 积分兑换商品页
	@RequestMapping(value = "toexchangepro")
	public String toexchangepro(Model model, HttpServletRequest request,
			HttpServletResponse response) {

		String style = request.getParameter("style");


		String wechatId = request.getParameter("wechatId"); // OpenId
		String ScoreExchangeId = request.getParameter("ScoreExchangeId"); // OpenId

		String uid = request.getParameter("uid");
		
		style = this.isStyle(new User(Long.valueOf(uid)));

		Long id = Long.parseLong(uid);

		User user = new User();
		user.setId(id);

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);

		model.addAttribute("topage", "toExchangeScore");

		// 兑换的列表
		ScoreExchange scoreExchange = scoreExchangeService.get(Long
				.parseLong(ScoreExchangeId.toString()));

		request.setAttribute("scoreExchange", scoreExchange);
		

		return "modules/member/themes/" + style + "/productShow";
	}

	
	
	//TODO 积分兑换操作
	@RequestMapping(value = "doexchange")
	public String doExchange(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		String style = request.getParameter("style");


		String score = request.getParameter("score");
		String proName = request.getParameter("proName");
		String seller = request.getParameter("seller");
		String flag = request.getParameter("flag");

		String wechatId = request.getParameter("wechatId"); // OpenId
		String mobile = request.getParameter("mobile"); // Mobile
		String exchangeId = request.getParameter("exchangeId"); // 对应的兑换项ID

		String exchangeToken = request.getParameter("exchangeToken");
		String uid = request.getParameter("uid");
		style = this.isStyle(new User(Long.valueOf(uid)));
		
		 

		
		model.addAttribute("flag", flag);
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", uid);
		request.setAttribute("style", style);
		model.addAttribute("topage", "toExchangeScore");

		Boolean b = MemberUtils
				.isToken(request, "exchangeToken", exchangeToken);

		if (b) {
			String message = "请勿重复提交";

			model.addAttribute("message", message);

			return "modules/member/themes/" + style + "/exchangeScoreOk";
		}

		User user = new User();
		
		
		
		user.setId(Long.parseLong(uid));

		// 需要判断是否已经登录过
		WechatMember member = this.isLogin(request, "" + uid);
		if (member == null) { // 没有登录先进入登录页面
			if ("34".equals(uid)) { // 阳光麦康处理
				member = wechatMemberService
						.getByWechatMemberId(user, wechatId);
				request.getSession(true).setAttribute("wechatUser" + wechatId,
						member);
			} else {

				request.setAttribute("topage", "exchangeScore");

				Map<String, Object> map = this.beforeLogin(uid, wechatId);

				model.addAttribute("login_mobile", map.get("mobile"));
				model.addAttribute("pwd", map.get("pwd"));
				model.addAttribute("reg", "reg");
				return "modules/member/themes/" + style + "/reg";

			}
		} else {

			// 查询兑换记录表：exchangeId

			ScoreExchange scoreExchange = scoreExchangeService.get(Long
					.parseLong(exchangeId));
			
			model.addAttribute("scoreExchange", scoreExchange);

			Integer count = scoreExchange.getCount();
			
			if (count == null) {
				count = 0;
			}
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("member_id", member.getId());
			map.put("exchange_id", exchangeId);
			
			String str = "";
			String cycleType  = scoreExchange.getCycleType();
			if(ScoreExchange.CYCLE_YEAR.equals(cycleType)){
				map.put("year", com.thinkgem.jeesite.common.utils.DateUtils.getYear());
				str = "今年";
			}else if(ScoreExchange.CYCLE_MONTH.equals(cycleType)){
				map.put("month", com.thinkgem.jeesite.common.utils.DateUtils.formatDate(new Date(), "yyyyMM"));
				str = "本月";
			}else if(ScoreExchange.CYCLE_DAY.equals(cycleType)){
				str = "今天";
				map.put("day",com.thinkgem.jeesite.common.utils.DateUtils.getTodayString());
			}
			
			
			Integer recordCount = memberService
					.selectExchangeRecordByMemberIdAndExchangeId(map);

			if (count > 0) {
				if (recordCount >= count) {
					String message = "亲,对不起,您"+str+"已经参与过" + recordCount
							+ "次兑换活动了已经超过了该兑换商品允许的范围，感谢您的参与，";

					model.addAttribute("message", message);

					return "modules/member/themes/" + style
							+ "/exchangeScoreOk";
				} else {
					String message = "恭喜您，已消费" + Integer.valueOf(score)/1000 + "积分成功兑换了【" + scoreExchange.getName()
							+ "】.";
					Integer myscore = member.getActiveScore();

					if (Integer.parseInt(score) > myscore) {
						message = "兑换失败,您目前活动的积分为" + myscore/1000 + "分,不能兑换积分为"
								+ Integer.valueOf(score)/1000 + "的【" +  scoreExchange.getName() + "】.";
					} else {
						// 写兑换记录
						ExchangeRecord recorder = new ExchangeRecord();
						recorder.setCostScore(Integer.parseInt(score));

						ScoreExchange exchange = new ScoreExchange();
						exchange.setId(Long.parseLong(exchangeId));
						recorder.setExchange(exchange);
						recorder.setMember(member);
						recorder.setName(scoreExchange.getName());
						
						if("52".equals(uid)){
							recorder.setType("1");
							recorder.setUser(scoreExchange.getUser());
						}else{
							recorder.setUser(user);
						}
						
						recorder.setValid(false);
						recorder.setUpdateTime(new Date());
						
						if(scoreExchange.isAutoClear()){
							recorder.setStatus(ExchangeRecord.STATUS_CLEAR);
						}else{
							recorder.setStatus(ExchangeRecord.STATUS_NORMAL);
						}
						
						 
						recorder.setEndTime(DateUtils.getDelayDate(scoreExchange.getValidDays()));
						recorder.setRemarks(message);

						// 保存兑换记录
						exchangeRecordService.save(recorder);

						model.addAttribute("recorder", recorder);
						// 积分消费记录
						ScoreUtils.addScore(member,-Integer.parseInt(score),"1","兑换【" + scoreExchange.getName() + "】使用了"+Double.parseDouble(score)/1000d+"个消费积分");
					}
					model.addAttribute("message", message);

					return "modules/member/themes/" + style
							+ "/exchangeScoreOk";
				}

			} else {
				String message = "恭喜您，已消费" + Integer.valueOf(score)/1000d + "积分成功兑换了【" + scoreExchange.getName()
						+ "】.";
				Integer myscore = member.getActiveScore();

				if (Integer.parseInt(score) > myscore) {
					message = "兑换失败,您目前的活动积分为" + myscore/1000d + "分,不能兑换积分为" + Integer.valueOf(score)/1000d
							+ "的【" + scoreExchange.getName() + "】.";
				} else {
					// 写兑换记录
					ExchangeRecord recorder = new ExchangeRecord();
					recorder.setCostScore(Integer.parseInt(score));

					ScoreExchange exchange = new ScoreExchange();
					exchange.setId(Long.parseLong(exchangeId));
					recorder.setExchange(exchange);
					recorder.setMember(member);
					recorder.setName(scoreExchange.getName());
					
					if("52".equals(uid)){
						recorder.setType("1");
						recorder.setUser(scoreExchange.getUser());
					}else{
						recorder.setUser(user);
					}
					
					recorder.setValid(false);
					recorder.setUpdateTime(new Date());


					if(scoreExchange.isAutoClear()){
						recorder.setStatus(ExchangeRecord.STATUS_CLEAR);
					}else{
						recorder.setStatus(ExchangeRecord.STATUS_NORMAL);
					}
					
					
					recorder.setEndTime(DateUtils.getDelayDate(scoreExchange.getValidDays()));
					recorder.setRemarks(message);

					// 保存兑换记录
					exchangeRecordService.save(recorder);
					
					user=systemService.getUser(user.getId());
					
					if(user.getInterfaceFlag()){
						UserMessageTemplate messageTemplate= userMessageTemplateService.getUserMessageTemplateByBid(user.getId(), BusinessMessageTemplate.SCORE_EXCHANGE);
						if(messageTemplate!=null){
							WeChat weChat=  weChatService.getWeChatByUserId(user.getId());
							String token = TokenUtils.getAPIToken(weChat);
							String date = com.thinkgem.jeesite.common.utils.DateUtils.formatDate(recorder.getEndTime(), "yyyy年MM月dd日 hh时mm分");
							TemplateMessage templateMessage=   TemplateMessageFactory.createScoreExchangeMessage(wechatId, messageTemplate.getTemplateId(), "您好，您已成功兑换产品。","产品名：", scoreExchange.getName(),scoreExchange.getScore()+"分", date+"前", "请在有效时间内兑奖");
							TemplateMessageUtils.sendTemplateMessage(token, templateMessage);
						}
					}

					model.addAttribute("recorder", recorder);
					// 积分消费记录
					ScoreUtils.addScore(member, -Integer.parseInt(score),"1","兑换【"+ scoreExchange.getName()+ "】使用了"+Double.parseDouble(score)/1000d+"个消费积分");
				}
				model.addAttribute("message", message);
				
				return "modules/member/themes/" + style + "/exchangeScoreOk";
			}

		}

		return "modules/member/themes/" + style + "/exchangeScore";

	}

	// -------------积分兑换----------------------------------------------------------------------------

	// -------------在线秒杀----------------------------------------------------------------------------
	//TODO 在线秒杀
	//新模析秒杀   进行单品倒计时页面
	@RequestMapping(value = "seckill")
	public String seckill(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId
		String mobile = request.getParameter("mobile"); // Mobile
		String seckillId = request.getParameter("seckillId"); // Mobile
		Long userId = 0L;
		
		if(seckillId==null){
			model.addAttribute("message", "seckillId参数为空");
			return "modules/member/themes/" + style + "/error";
		}
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		

		model.addAttribute("topage", "seckillist");

		try {
			userId = Long.parseLong(id);
		} catch (Exception e) {
			userId = 0L;
		}

		User user = new User();
		user.setId(userId);

		// 需要判断是否已经登录过

		WechatMember member = this.isLogin(request, id);
		
		//存储访问记录
		PageVisitExtendUtils.savePageVisit(request, user, member, PageVisit.PAGE_TYPE_SECKILL, null, "秒杀");
		
		
		if (member == null) { // 没有登录先进入登录页面
			if ("34".equals(id)) { // 阳光麦康处理
				member = wechatMemberService
						.getByWechatMemberId(user, wechatId);
				request.getSession(true).setAttribute("wechatUser" + userId,
						member);
			} else {

				Map<String, Object> map = this.beforeLogin(id, wechatId);

				model.addAttribute("login_mobile", map.get("mobile"));
				model.addAttribute("pwd", map.get("pwd"));
				
				model.addAttribute("reg", "reg");
				return "modules/member/themes/" + style + "/reg";

			}
		}

		Seckill seckill = new Seckill();

		seckill.setUser(user);
		EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
		entityManagerFactory.getCache().evict(Seckill.class);
		seckillService.clear();
		Seckill	seckill2= seckillService.get(Long.valueOf(seckillId));
		
		model.addAttribute("seckill", seckill2);
		model.addAttribute("nowDate",
				DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
		SeckillConfig config = SeckillExtendUtils
				.getSeckillConfigByUserId(userId);

		model.addAttribute("config", config);
		model.addAttribute("member", member);

		// 判断是否微信浏览器
		if (request.getHeader("user-agent").contains("MicroMessenger")) { // 是微信
			// 判断是否是盗链 (openId + ip =唯一)

		} else {
			addMessage(redirectAttributes, "请在微信中打开此页面!");
		}

		return "modules/member/themes/" + style + "/seckills";
	}
	
	
	//TODO 在线秒杀
	/**
	 * @author Jakemanse
	 * @time 2014-7-2  上午8:38:14
	 * @function <p> 老模板秒杀   还可以用 </p>
	 * @param request
	 * @param response
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "seckills")
	public String seckillist(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");
		


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId
		String mobile = request.getParameter("mobile"); // Mobile
		String seckillId = request.getParameter("seckillId"); // Mobile
		Long userId = 0L;
		
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		

		model.addAttribute("topage", "seckillist");

		try {
			userId = Long.parseLong(id);
		} catch (Exception e) {
			userId = 0L;
		}

		User user = new User();
		user.setId(userId);
		

		// 需要判断是否已经登录过

		WechatMember member = this.isLogin(request, id);
		
		
		
		if (member == null) { // 没有登录先进入登录页面
			if ("34".equals(id)) { // 阳光麦康处理
				member = wechatMemberService
						.getByWechatMemberId(user, wechatId);
				request.getSession(true).setAttribute("wechatUser" + userId,
						member);
			} else {

				Map<String, Object> map = this.beforeLogin(id, wechatId);

				model.addAttribute("login_mobile", map.get("mobile"));
				model.addAttribute("pwd", map.get("pwd"));
				
				model.addAttribute("reg", "reg");
				return "modules/member/themes/" + style + "/reg";

			}
		}

		Seckill seckill = new Seckill(); 
		//存储访问记录
		PageVisitExtendUtils.savePageVisit(request, user, member, PageVisit.PAGE_TYPE_SECKILL, null, "秒杀");
		

		seckill.setUser(user);
		
		 Page<Seckill>	page= seckillService.find(new Page<Seckill>(request, response), seckill);
		
		model.addAttribute("page", page);
		model.addAttribute("nowDate",
				DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
		SeckillConfig config = SeckillExtendUtils
				.getSeckillConfigByUserId(userId);

		model.addAttribute("config", config);
		model.addAttribute("member", member);

		// 判断是否微信浏览器
		if (request.getHeader("user-agent").contains("MicroMessenger")) { // 是微信
			// 判断是否是盗链 (openId + ip =唯一)

		} else {
			addMessage(redirectAttributes, "请在微信中打开此页面!");
		}

		return "modules/member/themes/" + style + "/seckills";
	}

	//TODO 在线秒杀微购物用
			@RequestMapping(value = "seckillListByShopping")
			public String seckillListByShopping(HttpServletRequest request,
					HttpServletResponse response, Model model,
					RedirectAttributes redirectAttributes) {

				String style = request.getParameter("style");


				String id = request.getParameter("uid"); // userId
				style = this.isStyle(new User(Long.valueOf(id)));
				String wechatId = request.getParameter("wechatId"); // OpenId
				String mobile = request.getParameter("mobile"); // Mobile
				String seckillId = request.getParameter("seckillId"); // Mobile
				Long userId = 0L;
				
				model.addAttribute("wechatId", wechatId);
				model.addAttribute("uid", id);
				request.setAttribute("style", style);
				

				model.addAttribute("topage", "seckillist");

				try {
					userId = Long.parseLong(id);
				} catch (Exception e) {
					userId = 0L;
				}

				User user = new User();
				user.setId(userId);
				
				

				// 需要判断是否已经登录过
				WechatMember member = this.isLogin(request, id);
				
				//存储访问记录
				PageVisitExtendUtils.savePageVisit(request, user, member, PageVisit.PAGE_TYPE_SECKILL, null, "秒杀");
				
				if (member == null) { // 没有登录先进入登录页面
					if ("34".equals(id)) { // 阳光麦康处理
						member = wechatMemberService
								.getByWechatMemberId(user, wechatId);
						request.getSession(true).setAttribute("wechatUser" + userId,
								member);
					} else {

						Map<String, Object> map = this.beforeLogin(id, wechatId);

						model.addAttribute("login_mobile", map.get("mobile"));
						model.addAttribute("pwd", map.get("pwd"));
						
						model.addAttribute("reg", "reg");
						return "modules/member/themes/" + style + "/reg";

					}
				}

				Seckill seckill = new Seckill(); 
				
				
				
				if("52".equals(id)){
					seckill.setType("1");
				}else{
					seckill.setUser(user);
				}
				
				 List<Seckill>	seckillList= seckillService.findAllByUserId(Long.parseLong(id));
				 
				 
				 
				// 兑换的列表
					
					List<Seckill> userList =  seckillService.findUserList();
					
					
					//对多用户下兑换列表进行处理
					
					List< List<Seckill>> map = new ArrayList< List<Seckill>>();
					for (int i = 0; i < userList.size(); i++) {
						 List<Seckill> temp = new  ArrayList<Seckill>();
						 for (int j = 0; j <seckillList.size(); j++) {
							if(userList.get(i).getUser().getId()==seckillList.get(j).getUser().getId()){
								temp.add(seckillList.get(j));
							}
						}
						 if(temp.size()!=0){
							 map.add(temp);
						 }
					}
				 
				
				model.addAttribute("map", map);
				model.addAttribute("nowDate",
						DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
				SeckillConfig config = SeckillExtendUtils
						.getSeckillConfigByUserId(userId);

				model.addAttribute("config", config);
				model.addAttribute("member", member);

				// 判断是否微信浏览器
				if (request.getHeader("user-agent").contains("MicroMessenger")) { // 是微信
					// 判断是否是盗链 (openId + ip =唯一)

				} else {
					addMessage(redirectAttributes, "请在微信中打开此页面!");
				}

				return "modules/member/themes/" + style + "/seckillListByShopping";
			}
	
	//TODO 在线秒杀
		@RequestMapping(value = "seckillList")
		public String seckillList(HttpServletRequest request,
				HttpServletResponse response, Model model,
				RedirectAttributes redirectAttributes) {

			String style = request.getParameter("style");


			String id = request.getParameter("uid"); // userId
			style = this.isStyle(new User(Long.valueOf(id)));
			String wechatId = request.getParameter("wechatId"); // OpenId
			String mobile = request.getParameter("mobile"); // Mobile
			String seckillId = request.getParameter("seckillId"); // Mobile
			Long userId = 0L;
			
			model.addAttribute("wechatId", wechatId);
			model.addAttribute("uid", id);
			request.setAttribute("style", style);
			

			model.addAttribute("topage", "seckillist");

			try {
				userId = Long.parseLong(id);
			} catch (Exception e) {
				userId = 0L;
			}

			User user = new User();
			user.setId(userId);
			
			

			// 需要判断是否已经登录过
			WechatMember member = this.isLogin(request, id);
			
			//存储访问记录
			PageVisitExtendUtils.savePageVisit(request, user, member, PageVisit.PAGE_TYPE_SECKILL, null, "秒杀");
			
			if (member == null) { // 没有登录先进入登录页面
				if ("34".equals(id)) { // 阳光麦康处理
					member = wechatMemberService
							.getByWechatMemberId(user, wechatId);
					request.getSession(true).setAttribute("wechatUser" + userId,
							member);
				} else {

					Map<String, Object> map = this.beforeLogin(id, wechatId);

					model.addAttribute("login_mobile", map.get("mobile"));
					model.addAttribute("pwd", map.get("pwd"));
					
					model.addAttribute("reg", "reg");
					return "modules/member/themes/" + style + "/reg";

				}
			}

			Seckill seckill = new Seckill(); 
			
			
			
			if("52".equals(id)){
				seckill.setType("1");
			}else{
				seckill.setUser(user);
			}
			
			 Page<Seckill>	page= seckillService.findByMember(new Page<Seckill>(request, response), seckill);
			
			model.addAttribute("page", page);
			model.addAttribute("nowDate",
					DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
			SeckillConfig config = SeckillExtendUtils
					.getSeckillConfigByUserId(userId);

			model.addAttribute("config", config);
			model.addAttribute("member", member);

			// 判断是否微信浏览器
			if (request.getHeader("user-agent").contains("MicroMessenger")) { // 是微信
				// 判断是否是盗链 (openId + ip =唯一)

			} else {
				addMessage(redirectAttributes, "请在微信中打开此页面!");
			}

			return "modules/member/themes/" + style + "/seckillList";
		}
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-27 下午3:31:04
	 * @function <p>
	 *           秒杀提交处理
	 *           </p>
	 * @param request
	 * @param response
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	//TODO 秒杀处理
	@RequestMapping(value = "doseckill")
	public String doseckill(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		String style = request.getParameter("style");

		Seckill seckill = new Seckill();
		Long userId = 0L;
		Long seckillId = 0L;

		request.setAttribute("style", style);
		model.addAttribute("topage", "seckillist");

		String flag = request.getParameter("flag"); // userId
		String id = request.getParameter("uid"); // userId
		String wechatId = request.getParameter("wechatId"); // OpenId
		
	
		model.addAttribute("flag", flag);
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		style = this.isStyle(new User(Long.valueOf(id)));

		try {
			seckillId = Long.parseLong(request.getParameter("seckill.id"));
			userId = Long.parseLong(request.getParameter("uid"));
		} catch (Exception e) {
			model.addAttribute("message", "您访问的页面不存在!");

			return "modules/member/themes/" + style + "/seckillsError";
		}
		
		
		Seckill temp=  seckillService.get(seckillId);

		seckill.setId(seckillId);
		User user = new User();
		user.setId(userId);

		WechatMember member = this.isLogin(request, "" + userId);

		ReturnResult rrResult = SeckillExtendUtils.doSeckill(seckill, member);
		SeckillConfig config = SeckillExtendUtils
				.getSeckillConfigByUserId(temp.getUser().getId());
		model.addAttribute("seckill", seckill);
		model.addAttribute("config", config);
		model.addAttribute("member", member);     
		model.addAttribute("returnResult", rrResult);
		if (rrResult.isSuccess()) {
			SeckillGainer sg = (SeckillGainer) rrResult.getParam();
			seckill = seckillService.get(seckill.getId());
			model.addAttribute("seckill", seckill);
			model.addAttribute("seckillGainer", sg);

			return "modules/member/themes/" + style + "/seckillsOk";
		} else {
			model.addAttribute("message", rrResult.getInfo());

			return "modules/member/themes/" + style + "/seckillsError";
		}
	}

	//TODO 退出登陆
	@RequestMapping(value = "logout")
	public String logout(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		String style = request.getParameter("style");

		String topage = request.getParameter("topage");
		String id = request.getParameter("uid");
		style = this.isStyle(new User(Long.valueOf(id)));

		request.setAttribute("style", style);

		String wechatId = request.getParameter("wechatId"); // OpenId

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		model.addAttribute("topage", topage);
		SessionMemberUtils.removeSession(request, "member_" + id, id);

		Map<String, Object> map = this.beforeLogin(id, wechatId);

		model.addAttribute("login_mobile", map.get("mobile"));
		model.addAttribute("pwd", map.get("pwd"));
		
		model.addAttribute("reg", "reg");
		return "modules/member/themes/" + style + "/reg";
	}

	// -------------在线秒杀----------------------------------------------------------------------------

	/**
	 * 判断商家样式
	 */
	//TODO 判断商家样式
	public String isStyle(String style) {
		String string = "";

		if (AssertUtils.isNullOrEmpty(style)) {
//			string = "default";
			string = "fashion";
			// string = "ShiShangHong" ;

		} else {
			string = style;
		}

		return string;
	}
	
	/**
	 * 判断商家样式
	 */
	//TODO 判断商家样式
	public String isStyle(User user) {
		String string = "";
		
		UserDefine userDefine= userDefineService.getByUserId(user.getId());
		
		if (AssertUtils.isNullOrEmpty(userDefine.getSiteStyle())) {
//			string = "default";
			string = "fashion";
			// string = "ShiShangHong" ;

		} else {
			string = userDefine.getSiteStyle();
		}

		return string;
	}
	
	/**
	 * 判断用户是否登陆
	 * 
	 * @return WechatMember null 没有登陆 ；
	 */
	//TODO 判断用户是否登陆
	public WechatMember isLogin(HttpServletRequest request, String uid) {

		String wechatId = request.getParameter("wechatId");
		User user=new User(Long.valueOf(uid));

		wechatMemberService.clear();
		
		WechatMember member = SessionMemberUtils.getSessionMemberByUserId(request, uid);
		//WechatMember member = null;
		if(member!=null){
			return member;
		}else{
			member = wechatMemberService.getByWechatMemberId(user, wechatId);
			if (member != null ) {
				SessionMemberUtils.addSessionValue(request,"member_" + uid, member);
			}
			return member;
		}
		
	}


	/**
	 * 获得oauth路径     url传入    /site/shopping
	 * @param url
	 * @param uid
	 * @param request
	 * @return
	 */
	public String getOAuthUrl(String url,String uid,HttpServletRequest request,HttpServletResponse response){

		String path = request.getContextPath();
		String basePath  = request.getScheme()+"://"+request.getServerName()+path;

		WeChat weChat =  weChatService.getWeChatByUserId(Long.parseLong(uid));
		String state = uid;
		url = url.replace("null", "");
		CookieUtils.setCookie(response, "redirectUrl", basePath+Global.getFrontPath()+url);
		
		System.out.println(basePath);

		String redirectUrl =URLEncoder.encode(basePath+"/f/oauth/redirect");

		String returnUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weChat.getAppId()+"&" +
				"redirect_uri="+redirectUrl+"&response_type=code&" +
				"scope=snsapi_base&state="+state+"&connect_redirect=1#wechat_redirect";
		return returnUrl;
	}
	
	
	
	/**
	 * 我的推荐
	 * 
	 * @throws UnsupportedEncodingException
	 */
	//TODO 我的推荐
	@RequestMapping(value = "mycommend")
	public String mycommend(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		List<WechatMember> wechatMemberList = new ArrayList<>();

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "mycommend");

		UserDefine userDefine  = WechatUtils.getUserDefineByUserId(Long.parseLong(id));
		
		style = this.isStyle(new User(Long.parseLong(id)));
		
		model.addAttribute("userDefine", userDefine);
		
		WechatMember member = this.isLogin(request, id);
		if (AssertUtils.notNull(member)) {

			wechatMemberList = wechatMemberService.findMyRecommandMembers(member.getRecommendCode());

			if (AssertUtils.notNull(wechatMemberList)) {
				if (wechatMemberList.size() < 1) {
					wechatMemberList = null;
				}
			}

			model.addAttribute("wechatMemberList", wechatMemberList);
			model.addAttribute("membersCount", (wechatMemberList!=null) ?wechatMemberList.size():0);

			return "modules/member/themes/" + style + "/myrecommend";

		} else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	// -----优惠券---------------------------

	/**
	 * 优惠券查询
	 * 
	 * @throws UnsupportedEncodingException
	 */
	//TODO 优惠券查询
	@RequestMapping(value = "findCoupon")
	public String findCoupon(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		String wechatId = request.getParameter("wechatId"); // OpenId
		
		style = this.isStyle(new User(Long.parseLong(id)));
		
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);

		model.addAttribute("topage", "findCoupon");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			List<Map<String, Object>> couponlist = memberService
					.selectecouponConfigByuserID(Integer.parseInt(id));

			if (AssertUtils.notNull(couponlist)) {
				if (couponlist.size() < 1) {
					couponlist = null;
				}
			}

			UserDefine userDefine = WechatUtils.getUserDefineByUserId(Long
					.parseLong(id));

			List list = new ArrayList();
			String couponTypeSwitch = userDefine.getCouponTypeSwitch();

			if (AssertUtils.isNullOrEmpty(couponTypeSwitch)) {
				couponTypeSwitch = "0";
			}

			if (couponTypeSwitch.equals("1")) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("user_id", id);
				list = wechatDaoHelper.selectCouponConfigByUserID(map);

			}

			model.addAttribute("couponlist", couponlist);
			model.addAttribute("couponTypeSwitch", couponTypeSwitch);
			model.addAttribute("ims_industry_type_list", list);

			return "modules/member/themes/" + style + "/coupon";

		} else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}
	
	
	
	@RequestMapping(value = "findCouponByShopping")
	public String findCouponByShopping(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		String wechatId = request.getParameter("wechatId"); // OpenId
		
		style = this.isStyle(new User(Long.parseLong(id)));
		
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);

		model.addAttribute("topage", "findCoupon");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			List<Map<String, Object>> couponlist = memberService
					.selectecouponConfigByuserID(Integer.parseInt(id));

			if (AssertUtils.notNull(couponlist)) {
				if (couponlist.size() < 1) {
					couponlist = null;
				}
			}

			UserDefine userDefine = WechatUtils.getUserDefineByUserId(Long
					.parseLong(id));

			List list = new ArrayList();
			String couponTypeSwitch = userDefine.getCouponTypeSwitch();

			if (AssertUtils.isNullOrEmpty(couponTypeSwitch)) {
				couponTypeSwitch = "0";
			}
			
		
			

			if (couponTypeSwitch.equals("1")) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("user_id", id);
				list = wechatDaoHelper.selectCouponConfigByUserID(map);
			}
			
			
			

			
			List<CouponConfig>  userList =   couponConfigService.findUserList();
			
			//对多用户下兑换列表进行处理
			
			Map<String, List<Map<String, Object>>> map = new HashMap<String, List<Map<String, Object> >>();
			for (int i = 0; i < userList.size(); i++) {
				 List<Map<String, Object> > temp = new  ArrayList<Map<String, Object> >();
				 for (int j = 0; j <couponlist.size(); j++) {
					if(userList.get(i).getUser().getId()== Long.parseLong(couponlist.get(j).get("user_id")+"")){
						temp.add(couponlist.get(j));
					}
				}
				 if(temp.size()!=0){
					 map.put(userList.get(i).getUser().getName(), temp);
				 }
			}
			
			
			model.addAttribute("map", map);
			
			
			
			
			
			model.addAttribute("couponlist", couponlist);
			model.addAttribute("couponTypeSwitch", couponTypeSwitch);
			model.addAttribute("ims_industry_type_list", list);

			return "modules/member/themes/" + style + "/findCouponByShopping";

		} else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}
	
	
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-25  下午2:58:53
	 * @function <p> 转向砸金蛋抽奖页面  </p>
	 * @param request
	 * @param response
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "toEggsLottery")
	public String toEggsLotteryPage(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes){

		String style = request.getParameter("style");

		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.parseLong(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId
		User user = new User();
		user.setId(Long.parseLong(id));

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "eggsLottery");

		String notice = "";

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.isNull(member)) {
			String url = getOAuthUrl("/member/toEggsLottery?a=1",id,request,response);
			return "redirect:"+url;
		}
		
		if (AssertUtils.notNull(member)) {

			List<Lottery> lotteryList = memberService
					.selectlotteryByuserId(Integer.parseInt(id),"1");

			if (AssertUtils.notNull(lotteryList)) {

				ProcessMessage message = new ProcessMessage();
				message.setMessageType(Message.MSG_TYPE_TEXT);
				LotteryConfig config = lotteryConfigService.getByUserId(Long
						.parseLong(id));

				if (config == null || !config.getStartup()) {
					notice = "亲,对不起，抽奖活动还没有启动或已经停止，请参与其它的活动吧!";
					model.addAttribute("notice", notice);

					return "modules/member/themes/" + style + "/lotteryError";

				}

				// 判断今天是否已经参与过抽奖活动
				Date date = new Date();
				date.setHours(0);
				date.setMinutes(0);
				date.setSeconds(0);

				List<LotteryLog> lotList = lotteryLogService
						.findByMemberIdAndDate(Long.parseLong(id),
								member.getId(), date);
				if (config.getRepeats()) { // 请允许复重
					if (lotList != null && !lotList.isEmpty()
							&& lotList.size() >= config.getRepeatCount()) {
						notice = "亲,对不起,您今天已经参与过" + lotList.size()
								+ "次抽奖活动了已经超过了允许的范围，感谢您的参与，明天继续，本次不扣除您的积分.";
						// this.saveLotteryLog(member, null,user);
						model.addAttribute("notice", notice);

						return "modules/member/themes/" + style
								+ "/lotteryError";
					}

				} else {// 不允许重复抽奖
					if (lotList != null && !lotList.isEmpty()) {
						notice = "亲,对不起,您今天已经参与过抽奖活动了，感谢您的参与，明天继续，本次不扣除您的积分.";
						// this.saveLotteryLog(member, null,user);
						model.addAttribute("notice", notice);

						return "modules/member/themes/" + style
								+ "/lotteryError";
					}

				}

				// 看是否有未消费的奖品如果有则不允许再抽取
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("userId", id);
				params.put("memberId", member.getId() + "");
				List myLtyLst = wechatDaoHelper
						.queryMineLotteryRecordByMember(params);
				if (myLtyLst != null && !myLtyLst.isEmpty()) {

					// queryMineLottery(member);
					// return null;

					notice = "亲,对不起,您还有" + myLtyLst.size()
							+ "个奖品未使用，暂时无法参与本次抽奖,请在我的奖品页面，查看自己获得奖品。谢谢！";
					// this.saveLotteryLog(member, null,user);
					model.addAttribute("notice", notice);

					return "modules/member/themes/" + style + "/lotteryError";
				}

				// 判断积分是否充足
				if (member.getActiveScore() < config.getCostScore()) {
					notice = "亲,对不起,你当前的积分不足,每次抽奖最低需要" + config.getCostScore()/1000
							+ "积分,谢谢您的参与,试试签到获得积分吧!";
					model.addAttribute("notice", notice);

					return "modules/member/themes/" + style + "/lotteryError";
				}

				List<Lottery> lotteryList1 = lotteryService
						.getUserLotteryByUserId(Long.parseLong(id));

				if (!(lotteryList1 != null && !lotteryList1.isEmpty())) {

					notice = "亲,对不起，抽奖活动还没有启动，请参与其它的活动吧!";
					model.addAttribute("notice", notice);

					return "modules/member/themes/" + style + "/lotteryError";
				}

				else {

					model.addAttribute("lotteryList", lotteryList1);

					if (AssertUtils.isNull(config.getRepeatCount())) {
						config.setRepeatCount(1);
					} else {
						if (config.getRepeatCount() < 1) {
							config.setRepeatCount(1);
						}
					}

					model.addAttribute("count", config.getRepeatCount());
					
					model.addAttribute("mycount", lotList.size());
					model.addAttribute("config", config);

					return "modules/member/themes/" + style + "/eggsLottery";
				}
			} else {

				notice = "商家暂无抽奖活动，敬请期待！！！";
				model.addAttribute("notice", notice);

				return "modules/member/themes/" + style + "/lotteryError";
			}

		} else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");

			return "modules/member/themes/" + style + "/reg";
		}
		
		
		
	}
	
	
	
	/**
	 * 无会员砸金蛋跳转
	 *@author xiaoqian
	 * @param request
	 * @param response
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * 2014-10-16下午3:33:47
	 */
	@RequestMapping(value = "toEggsLotteryPageNotMeb")
	public String toEggsLotteryPageNotMeb(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes){

		String style = request.getParameter("style");

		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.parseLong(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId
		User user = new User();
		user.setId(Long.parseLong(id));

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "eggsLottery");

		String notice = "";

		WechatMember member = this.isLogin(request, id);


			List<Lottery> lotteryList = memberService
					.selectlotteryByuserId(Integer.parseInt(id),"5");

			if (AssertUtils.notNull(lotteryList)) {

				ProcessMessage message = new ProcessMessage();
				message.setMessageType(Message.MSG_TYPE_TEXT);
				LotteryConfig config = lotteryConfigService.getByUserId(Long
						.parseLong(id));

				if (config == null || !config.getStartup()) {
					notice = "亲,对不起，抽奖活动还没有启动或已经停止，请参与其它的活动吧!";
					model.addAttribute("notice", notice);

					return "modules/member/themes/" + style + "/lotteryError";

				}

				// 判断今天是否已经参与过抽奖活动
				Date date = new Date();
				date.setHours(0);
				date.setMinutes(0);
				date.setSeconds(0);
				
				
				List<LotteryLog> lotList =null;
				
				if(member!=null){
					
					lotList = lotteryLogService
							.findByMemberIdAndType(Long.parseLong(id),
									member.getId(), 7);
				}
					if (lotList != null && !lotList.isEmpty()) {
						notice = "亲,对不起,您已经参与过抽奖活动了，感谢您的参与，本次不扣除您的积分.";
						// this.saveLotteryLog(member, null,user);
						model.addAttribute("notice", notice);

						return "modules/member/themes/" + style
								+ "/lotteryError";
					}


				// 判断积分是否充足
//				if (member.getScore() < config.getCostScore()) {
//					notice = "亲,对不起,你当前的积分不足,每次抽奖最低需要" + config.getCostScore()
//							+ "积分,谢谢您的参与,试试签到获得积分吧!";
//					model.addAttribute("notice", notice);
//
//					return "modules/member/themes/" + style + "/lotteryError";
//				}

				List<Lottery> lotteryList1 = lotteryService
						.getUserLotteryByUserIdNotMeb(Long.parseLong(id));
				if (!(lotteryList1 != null && !lotteryList1.isEmpty())) {

					notice = "亲,对不起，抽奖活动还没有启动，请参与其它的活动吧!";
					model.addAttribute("notice", notice);

					return "modules/member/themes/" + style + "/lotteryError";
				}

				else {

					model.addAttribute("lotteryList", lotteryList1);

					if (AssertUtils.isNull(config.getRepeatCount())) {
						config.setRepeatCount(1);
					} else {
						if (config.getRepeatCount() < 1) {
							config.setRepeatCount(1);
						}
					}

					model.addAttribute("member", member);
					model.addAttribute("count", config.getRepeatCount());
					
					model.addAttribute("config", config);

					return "modules/member/themes/" + style + "/eggsLotteryByNotMeb";
				}
			} else {

				notice = "您所在的商家暂无抽奖活动";
				model.addAttribute("notice", notice);

				return "modules/member/themes/" + style + "/lotteryError";
			}
	}
	
	
	
	/**
	 * 
	 *@author xiaoqian
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * 2014-10-16下午5:34:12
	 */
	@RequestMapping(value = "doLotteryByNotMeb")
	public String doLotteryByNotMeb(Model model, HttpServletRequest request,
			HttpServletResponse response) {

		String id = request.getParameter("uid");
		String mobile = request.getParameter("mobile");
		String lotteryId = request.getParameter("lotteryId");
		String wechatId = request.getParameter("wechatId"); // OpenId
		
		JSONObject jsonObj = new JSONObject();		//JSON
		
		Lottery lottery =  lotteryService.get(Long.parseLong(lotteryId));
		WechatMember member = this.isLogin(request, id);
		
		User user=new User(Long.parseLong(id));
		
		
		WechatMember wechatMember = wechatMemberService.getByWechatMemberId(
				user, wechatId);
		if(mobile!=null){
			if(!mobile.equals(member.getMobile())){
				member.setMobile(mobile);
				wechatMemberService.save(wechatMember);
			}
		}
		
		
		
		
		saveLotteryLogByNotMeb(wechatMember, lottery, user,7); // 中奖日志
		
		jsonObj.put("success", "0");
		
		writeJson(request, response, jsonObj);
		return null;
	}
	
	
	
	
	/**
	 * 无会员注册砸金蛋
	 *@author xiaoqian
	 * @param request
	 * @param response
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * 2014-10-16下午3:32:48
	 */
	@RequestMapping(value = "doEggsLotteryByNotMeb")
	public String doEggsLotteryByNotMeb(HttpServletRequest request,	HttpServletResponse response, Model model,	RedirectAttributes redirectAttributes){
		

		String style = request.getParameter("style");

		
		Map<String ,String> resMap = new HashMap<String ,String>();

		String uid = request.getParameter("uid");
		String wechatId  =  request.getParameter("wechatId");
		
		style = this.isStyle(new User(Long.parseLong(uid)));

		String reply = "";
		String message = "";

		User user = new User();

		user.setId(Long.parseLong(uid));

		WechatMember member = this.isLogin(request, uid);
		
		if(member == null){
			member=new WechatMember();
			member.setUser(user);
			member.setWechatId(wechatId);
			member.setScore(0);
			member.setActiveScore(0);
			member.setConsumeScore(0);
			member.setCreditScore(0);
			member.setName("匿名");
			// wechatMember.setBirthday(birthday);
			member.setSex("保密");
			member.setMobile("");
			// wechatMember
			// .setPassword(EncryptUtils.MD5EncodeString(password));
			member.setLastSignTime(null);
			member.setIsRandomPassword(false);
			wechatMemberService.save(member);
		}

		LotteryConfig config = lotteryConfigService.getByUserId(Long.parseLong(uid));
		
		JSONObject jsonObj = new JSONObject();		//JSON
		Lottery mylottery = null;
		List<Lottery> lotteryList = lotteryService.getUserLotteryByUserIdNotMeb(Long
				.parseLong(uid));
		if (lotteryList != null && !lotteryList.isEmpty()) {
			
			
			//验证是否启动
			if(config == null  || !config.getStartup()){
				message = "亲,对不起，抽奖活动还没有启动或已经停止，请参与其它的活动吧!";

				jsonObj.put("lotteryName", "没有中任何奖品");
				jsonObj.put("message", message);
				jsonObj.put("success", "0");
				
				writeJson(request, response, jsonObj);
				return null;
			}
			
			
			//验证是否有未使用的奖品
			
			//判断今天是否已经参与过抽奖活动
			Date date = new Date();
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			
			
			List<LotteryLog> lotList =null;
			
			if(member!=null){
				lotList =  lotteryLogService.findByMemberIdAndType(user.getId(),member.getId(), 7);
				if(lotList != null && !lotList.isEmpty()){
					message = "亲,对不起,您今天已经参与过抽奖活动了，感谢您的参与，本次不扣除您的积分.";
					
					jsonObj.put("lotteryName", "没有中任何奖品");
					jsonObj.put("message", message);
					jsonObj.put("success", "0");
					
					writeJson(request, response, jsonObj);
					return null;
				}
			}
			
				
			
			//看是否有未消费的奖品如果有则不允许再抽取
				
				/*
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("userId", user.getId()+"");
			params.put("memberId", member.getId()+"");
			List myLtyLst = wechatDaoHelper.queryMineLotteryRecordByMember(params);
			if(myLtyLst != null && !myLtyLst.isEmpty()){
				
//				queryMineLottery(member);
//				return null;
				Map<String,Object> rst = (Map<String,Object>)myLtyLst.get(0);
				message = "亲,对不起,您还有"+myLtyLst.size()+"个奖品未使用，暂时无法参与本次抽奖,请回复【我的抽奖】，查看自己获得奖品，核销使用后再次抽奖,如果您想放弃本奖品请输入【放弃"+rst.get("id")+"】，谢谢！";
				
				jsonObj.put("lotteryName", "没有中任何奖品");
				jsonObj.put("message", message);
				jsonObj.put("success", "0");
				writeJson(request, response, jsonObj);
				saveLotteryLog(member, null);
				return null;
			}
			*/

			
			// 抽奖动作
			MemberUtils mUtils = new MemberUtils();
			Lottery lottery = mUtils.extractLottery(lotteryList, config);

			mylottery = lottery;
			if (lottery == null) {
				reply = "再接再励 ";
				message = "太可惜了竟然与奖品擦肩而过!";


				jsonObj.put("lotteryName", reply);
				jsonObj.put("success", "0");
				jsonObj.put("message", message);
				
				saveLotteryLogByNotMeb(member, lottery, user,7); // 中奖日志

				writeJson(request, response, jsonObj);
				return null;
			} else {

				jsonObj.put("lotteryName", lottery.getName());
				jsonObj.put("message", message);
				jsonObj.put("success", "1");
				jsonObj.put("lotteryId",lottery.getId());
				

				writeJson(request, response, jsonObj);
				
				return null;

			}

		}
		return null;
	}
	
	
	
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-26  上午9:20:25
	 * @function <p> 会员砸金蛋 处理 </p>
	 * @param request
	 * @param response
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "doEggsLottery")
	public String doEggsLottery(HttpServletRequest request,	HttpServletResponse response, Model model,	RedirectAttributes redirectAttributes){
		

		String style = request.getParameter("style");

		
		Map<String ,String> resMap = new HashMap<String ,String>();

		String uid = request.getParameter("uid");
		String wechatId  =  request.getParameter("wid");
		
		style = this.isStyle(new User(Long.parseLong(uid)));

		String reply = "";
		String message = "";

		User user = new User();

		user.setId(Long.parseLong(uid));

		WechatMember member = this.isLogin(request, uid);
		
		if(member == null){
			member = wechatMemberService.getByWechatMemberId(user, wechatId);
		}

		LotteryConfig config = lotteryConfigService.getByUserId(Long.parseLong(uid));
		
		JSONObject jsonObj = new JSONObject();		//JSON
		Lottery mylottery = null;
		List<Lottery> lotteryList = lotteryService.getUserLotteryByUserId(Long
				.parseLong(uid));
		if (lotteryList != null && !lotteryList.isEmpty()) {
			
			
			//验证是否启动
			if(config == null  || !config.getStartup()){
				message = "亲,对不起，抽奖活动还没有启动或已经停止，请参与其它的活动吧!";

				jsonObj.put("lotteryName", "没有中任何奖品");
				jsonObj.put("message", message);
				jsonObj.put("success", "0");
				
				writeJson(request, response, jsonObj);
				return null;
			}
			
			
			//验证是否有未使用的奖品
			
			//判断今天是否已经参与过抽奖活动
			Date date = new Date();
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			
			
			List<LotteryLog> lotList =  lotteryLogService.findByMemberIdAndDate(user.getId(),member.getId(), date);
			if(config.getRepeats()){	//请允许复重
				if(lotList != null && !lotList.isEmpty() && lotList.size()>=config.getRepeatCount()){
					message = "亲,对不起,您今天已经参与过"+lotList.size()+"次抽奖活动了已经超过了允许的范围，感谢您的参与，明天继续，本次不扣除您的积分.";
					
					jsonObj.put("lotteryName", "没有中任何奖品");
					jsonObj.put("message", message);
					jsonObj.put("success", "0");
					
					saveLotteryLog(member, null);
					return null;
				}
				
			}else{//不允许重复抽奖
				if(lotList != null && !lotList.isEmpty()){
					message = "亲,对不起,您今天已经参与过抽奖活动了，感谢您的参与，明天继续，本次不扣除您的积分.";

					jsonObj.put("lotteryName", "没有中任何奖品");
					jsonObj.put("message", message);
					jsonObj.put("success", "0");
					
					saveLotteryLog(member, null);
					return null;
				}
				
			}
			
			//看是否有未消费的奖品如果有则不允许再抽取
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("userId", user.getId()+"");
			params.put("memberId", member.getId()+"");
			List myLtyLst = wechatDaoHelper.queryMineLotteryRecordByMember(params);
			if(myLtyLst != null && !myLtyLst.isEmpty()){
				
//				queryMineLottery(member);
//				return null;
				Map<String,Object> rst = (Map<String,Object>)myLtyLst.get(0);
				message = "亲,对不起,您还有"+myLtyLst.size()+"个奖品未使用，暂时无法参与本次抽奖,请回复【我的抽奖】，查看自己获得奖品，核销使用后再次抽奖,如果您想放弃本奖品请输入【放弃"+rst.get("id")+"】，谢谢！";
				
				jsonObj.put("lotteryName", "没有中任何奖品");
				jsonObj.put("message", message);
				jsonObj.put("success", "0");
				writeJson(request, response, jsonObj);
				saveLotteryLog(member, null);
				return null;
			}
			
			
			
			//验证是否有足够的积分
			if(member.getActiveScore() <  config.getCostScore()){
				message = "亲,对不起,你当前的积分不足,每次抽奖最低需要"+config.getCostScore()/1000+"积分,谢谢您的参与,试试签到获得积分吧!";
				jsonObj.put("lotteryName", "没有中任何奖品");
				jsonObj.put("message", message);
				jsonObj.put("success", "0");
				writeJson(request, response, jsonObj);
				saveLotteryLog(member, null);
				return null;
			}
			
			

			// 扣除积分
			member.setActiveScore(member.getActiveScore()-config.getCostScore());
			member.setScore(member.getScore() - config.getCostScore());
			wechatMemberService.save(member);
			ScoreUtils.addWechatMemberCostScore(member,
					config.getCostScore(), "参与砸金抽奖活动消费积分.");
			
			
			// 抽奖动作
			MemberUtils mUtils = new MemberUtils();
			Lottery lottery = mUtils.extractLottery(lotteryList, config);

			mylottery = lottery;
			if (lottery == null) {
				reply = "再接再励 ";
				message = "太可惜了竟然与奖品擦肩而过!";
				this.saveLotteryLog(member, null, user);


				jsonObj.put("lotteryName", reply);
				jsonObj.put("success", "0");
				jsonObj.put("message", message);
				jsonObj.put("mycount", lotList.size());

				writeJson(request, response, jsonObj);
				return null;
			} else {

				LotteryRecord record = new LotteryRecord();
				record.setEndTime(DateUtils.getDelayDate(config.getValidDays()));
				record.setLottery(lottery);
				record.setMember(member);
				record.setName(lottery.getName());
				record.setSourceType(LotteryRecord.SOURCE_TYPE_ME);
				record.setStatus(LotteryRecord.STATUS_NORMAL);
				record.setUser(user);
				// 中奖记录
				lotteryRecordService.save(record);

				saveLotteryLog(member, lottery, user); // 中奖日志

				// 判断是否还有余下的该奖品
				String validDate = DateUtils.formatDate(
						(record.getEndTime() == null) ? new Date() : record
								.getEndTime(), "MM月dd日");
				message = "恭喜您，本次获得了[" + lottery.getName() + "]奖品,请于"
						+ validDate + "之前到店里凭二维码核销使用,过期作废.";
				if (lottery.getScore() != null && lottery.getScore() > 0) {
					ScoreUtils.addScore(member, lottery.getScore(),"0","会员中奖");

					// 加完积分后直接核销
					if (record.getLottery() != null
							&& Lottery.YES.equals(record.getLottery()
									.getAutoClear())) {
						record.setStatus(LotteryRecord.STATUS_CLEAR);
						record.setUpdateTime(new Date());
						record.setRemarks("成功增了" + lottery.getScore()/1000d
								+ "个积分并由系统自动核销.");
						lotteryRecordService.save(record);
					}

					message = "恭喜您，本次获得了[" + lottery.getName() + "]奖品,您成功增了"
							+ lottery.getScore()/1000d + "个积分。";
				}
				String title = "恭喜您中奖了";
				String desc = reply;
				if (StringUtils.isNotEmpty(config.getQrcodeTitle())) {
					title = config.getQrcodeTitle();
				}
				if (StringUtils.isNotEmpty(config.getQrcodeDesc())) {
					desc = config.getQrcodeDesc();
				}

				jsonObj.put("lotteryName", lottery.getName());
				jsonObj.put("message", message);
				jsonObj.put("success", "1");
				jsonObj.put("mycount", lotList.size());
				

				writeJson(request, response, jsonObj);
				
				return null;

			}

		}
		return null;
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-26  下午2:12:36
	 * @function <p> 保存抽奖日志 </p>
	 * @param member
	 * @param mylottery
	 */
	public void saveLotteryLog(WechatMember member,Lottery mylottery){
		LotteryLog lotteryLog = new LotteryLog();
		lotteryLog.setMember(member);
		lotteryLog.setType(LotteryRecord.SOURCE_TYPE_ME);
		lotteryLog.setName((mylottery==null)?null:mylottery.getName());
		lotteryLog.setUser(member.getUser());
		lotteryLog.setStatus(LotteryLog.STATUS_NORMAL);
		lotteryLog.setRemarks("参与砸金蛋抽奖。");
		
		lotteryLogService.save(lotteryLog);
	}
	

	/**
	 * 优惠券条件查询
	 * 
	 * @throws UnsupportedEncodingException
	 */
	//TODO 优惠券条件查询
	@RequestMapping(value = "findCouponByArgs")
	public String findCouponByArgs(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes)
			throws UnsupportedEncodingException {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		String wechatId = request.getParameter("wechatId"); // OpenId
		
		style = this.isStyle(new User(Long.parseLong(id)));
		
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);

		model.addAttribute("topage", "findCoupon");

		WechatMember member = this.isLogin(request, id);

		String ims_industry_type = request.getParameter("ims_industry_type");

		ims_industry_type = new String(ims_industry_type.getBytes("ISO8859-1"),
				"utf-8");

		// 根据 ims_industry_type 查询

		if (AssertUtils.notNull(member)) {
			List<Map<String, Object>> couponlist = new ArrayList<Map<String, Object>>();

			if (AssertUtils.isNullOrEmpty(ims_industry_type)
					|| ims_industry_type.equals("全部")) {
				couponlist = memberService.selectecouponConfigByuserID(Integer
						.parseInt(id));
			} else {
				Map<String, Object> map = new HashMap<String, Object>();

				map.put("user_id", id);
				map.put("ims_industry_type", ims_industry_type);

				couponlist = memberService.selectecouponConfigByArgs(map);

			}

			if (AssertUtils.notNull(couponlist)) {
				if (couponlist.size() < 1) {
					couponlist = null;
				}
			}

			UserDefine userDefine = WechatUtils.getUserDefineByUserId(Long
					.parseLong(id));

			List list = new ArrayList();
			String couponTypeSwitch = userDefine.getCouponTypeSwitch();

			if (AssertUtils.isNullOrEmpty(couponTypeSwitch)) {
				couponTypeSwitch = "0";
			}

			if (couponTypeSwitch.equals("1")) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("user_id", id);
				list = wechatDaoHelper.selectCouponConfigByUserID(map);

			}

			model.addAttribute("couponlist", couponlist);
			model.addAttribute("couponTypeSwitch", couponTypeSwitch);
			model.addAttribute("ims_industry_type_list", list);

			return "modules/member/themes/" + style + "/coupon";

		} else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	/**
	 * 优惠券生成
	 * 
	 * @throws UnsupportedEncodingException
	 */
	//TODO 优惠券生成
	@RequestMapping(value = "coupon")
	public String coupon(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");

		String id = request.getParameter("uid"); // userId
		String flag = request.getParameter("flag"); // userId
		
		style = this.isStyle(new User(Long.parseLong(id)));
		
		String wechatId = request.getParameter("wechatId"); // OpenId
		String couponConfigID = request.getParameter("couponConfigID"); // 优惠券配置ID
		String couponToken = request.getParameter("couponToken");

		model.addAttribute("topage", "findCoupon");

		String reply = "";

		model.addAttribute("flag", flag);
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);

		WechatMember member = this.isLogin(request, id);

		CouponConfig couponConfig = couponConfigService.get(Long
				.parseLong(couponConfigID));
		if (AssertUtils.notNull(member)) {


			Boolean b = MemberUtils.isToken(request, "coupon_token",
					couponToken);

			if (b) {
				model.addAttribute("coupon", null);

				reply = "请勿重复提交！";
				model.addAttribute("reply", reply);

				return "modules/member/themes/" + style + "/couponMessage";
			}

			if (couponConfig == null) {// 未找到对应的优惠券
				reply = "亲,对不起，您输入的格式不正确无法找到对应的优惠券,请查证后再重新输入获取,谢谢!";
				model.addAttribute("reply", reply);

				return "modules/member/themes/" + style + "/couponMessage";
			}
			if (!couponConfig.getRepeats()) { // 不允许重复的话
				Map<String, String> params = new HashMap<String, String>();

				params.put("userId", member.getUser().getId() + "");
				params.put("memberId", member.getId() + "");
				params.put("configId", couponConfig.getId() + "");
				int cnt = wechatDaoHelper.getMyTodayCouponCount(params);
				if (cnt > 0) {
					reply = "亲,对不起，您已经获取过当天的【" + couponConfig.getName()
							+ "】了,无法再重复获取,每人每天只能获取一份同一种类的优惠券,谢谢!";
					List<Map<String, Object>> myCoupons = wechatDaoHelper
							.queryCoupons(params);
					Map<String, Object> couponMap = myCoupons.get(0);
					Long qrcodeId = Long.parseLong(couponMap.get("qrcode_id")
							.toString());
					String title = "您有未使用的微会员特价【" + couponMap.get("name") + "】";

					Date endTime = (Date) couponMap.get("end_time");

					String validDate = DateUtils.formatDate(
							(endTime == null) ? new Date() : endTime, "MM月dd日");
					String desc = "您有未使用的【" + couponConfig.getName() + "】,请于"
							+ validDate + "之前到店里使用后再重新获取吧,过期作废，谢谢！";

					model.addAttribute("reply", reply);

					return "modules/member/themes/" + style + "/couponMessage";

				}
			} else { // 允许重但超多最多次数
				Map<String, String> params = new HashMap<String, String>();

				params.put("userId", member.getUser().getId() + "");
				params.put("memberId", member.getId() + "");
				params.put("configId", couponConfig.getId() + "");
				int cnt = wechatDaoHelper.getMyTodayCouponCount(params);
				if (couponConfig.getRepeatCount() != null
						&& couponConfig.getRepeatCount() != 0) { // 0代表无限次数

					if (cnt >= couponConfig.getRepeatCount()) {
						reply = "亲,对不起，您有" + cnt
								+ "个微会员特价优惠券还未使用,无法再重复获取，请将已获得的优惠使用后再重新获取,谢谢!";
						// 此处应该将已生的发给用户
						List<Map<String, Object>> myCoupons = wechatDaoHelper
								.queryCoupons(params);
						if (cnt == 1) {
							Map<String, Object> couponMap = myCoupons.get(0);
							Long qrcodeId = Long.parseLong(couponMap.get(
									"qrcode_id").toString());
							String title = "您有未使用的微会员特价【"
									+ couponMap.get("name") + "】";

							Date endTime = (Date) couponMap.get("end_time");

							String validDate = DateUtils.formatDate(
									(endTime == null) ? new Date() : endTime,
									"MM月dd日");
							String desc = "您有未使用的【" + couponConfig.getName() + "】,请于"
									+ validDate + "之前到店里使用后再重新获取吧,过期作废，谢谢！";

							model.addAttribute("reply", reply);

							return "modules/member/themes/" + style
									+ "/couponMessage";

						} else {

							List<NewsReply> newsReplies = new ArrayList<NewsReply>();
							for (Map<String, Object> map : myCoupons) {
								String title = "您有未使用的微会员特价【" + map.get("name")
										+ "】";
								Date date = (Date) map.get("end_time");
								String validDate = DateUtils.formatDate(
										(date == null) ? new Date() : date,
										"MM月dd日");
								String desc = "亲，您有未使用的微会员特价【"
										+ map.get("name") + "】,请于" + validDate
										+ "之前到店里凭此二维码核销使用，过期作废，谢谢！";
								Long qrcodeId = Long.parseLong(map.get(
										"qrcode_id").toString());
								NewsReply newsReply = new NewsReply();
								newsReply.setTitle(title);
								newsReply.setDescription(desc);
								newsReply.setPicUrl(QRCodeUtils
										.getQRCodePNGURL(qrcodeId));
								newsReply.setUrl(QRCodeUtils
										.getQRCodePNGURL(qrcodeId));

								newsReplies.add(newsReply);
							}

							model.addAttribute("reply", reply);

							return "modules/member/themes/" + style
									+ "/couponMessage";

						}
					}
				}

			}

			// 有未使用的优惠

			
			

			String title = "微会员特权优惠券";
			if (couponConfig != null
					&& StringUtils.isNotEmpty(couponConfig.getQrcodeTitle())) {
				title = couponConfig.getQrcodeTitle();
			}
			
			
			if (couponConfig != null
					&& StringUtils.isNotEmpty(couponConfig.getQrcodeDesc())) {
				reply = couponConfig.getQrcodeDesc();
			}
			model.addAttribute("reply", reply);

			return "modules/member/themes/" + style + "/couponMessage";

		} else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	// --------优惠券-------
	/**
	 * 返回主页
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	//TODO 返回主页
	@RequestMapping(value = "toIndex")
	public String toIndex(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.parseLong(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		model.addAttribute("style", style);
		model.addAttribute("uid", id);
		model.addAttribute("wechatId", wechatId);

		String topage = request.getParameter("topage");

		model.addAttribute("topage", topage);

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {
			request.setAttribute("wechatMember", member);
			
			
			return "modules/member/themes/" + style + "/memberCenter";
		} else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	/**
	 * 我的奖品跳到二维码页面
	 * 
	 * @throws UnsupportedEncodingException
	 */
	//TODO 我的奖品跳到二维码页面
	@RequestMapping(value = "qrcode")
	public String qrcode(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes)
			throws UnsupportedEncodingException {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		
		style = this.isStyle(new User(Long.parseLong(id)));
		
		String wechatId = request.getParameter("wechatId"); // OpenId
		String topage = request.getParameter("topage");

		model.addAttribute("topage", topage);

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		

		String codeID = request.getParameter("codeID");

		String name = request.getParameter("name");

		name = new String(name.getBytes("ISO8859-1"), "utf-8");

		model.addAttribute("name", name);

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			model.addAttribute("codeID", codeID);
			
			//传入商品的用户id
			String userId = request.getParameter("userId");
			User user= systemService.getUser(Long.valueOf(userId));
			
			
			model.addAttribute("user", user);

			return "modules/member/themes/" + style + "/myQRCode";

		} else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}
	}

	// 0-------抽奖--------
	/**
	 * 刮刮卡 *
	 * 
	 * @throws UnsupportedEncodingException
	 */
	//TODO 抽奖
	@RequestMapping(value = "guaguaka")
	public String guaguaka(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.parseLong(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		User user = new User();

		user.setId(Long.parseLong(id));

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "guaguaka");

		String notice = "";

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			List<Lottery> lotteryList = memberService
					.selectlotteryByuserId(Integer.parseInt(id),"1");

			if (AssertUtils.notNull(lotteryList)) {

				ProcessMessage message = new ProcessMessage();
				message.setMessageType(Message.MSG_TYPE_TEXT);
				LotteryConfig config = lotteryConfigService.getByUserId(Long
						.parseLong(id));

				if (config == null || !config.getStartup()) {
					notice = "亲,对不起，抽奖活动还没有启动或已经停止，请参与其它的活动吧!";
					model.addAttribute("notice", notice);

					return "modules/member/themes/" + style + "/lotteryError";

				}

				// 判断今天是否已经参与过抽奖活动
				Date date = new Date();
				date.setHours(0);
				date.setMinutes(0);
				date.setSeconds(0);

				List<LotteryLog> lotList = lotteryLogService
						.findByMemberIdAndDate(Long.parseLong(id),
								member.getId(), date);
				if (config.getRepeats()) { // 请允许复重
					if (lotList != null && !lotList.isEmpty()
							&& lotList.size() >= config.getRepeatCount()) {
						notice = "亲,对不起,您今天已经参与过" + lotList.size()
								+ "次抽奖活动了已经超过了允许的范围，感谢您的参与，明天继续，本次不扣除您的积分.";
						// this.saveLotteryLog(member, null,user);
						model.addAttribute("notice", notice);

						return "modules/member/themes/" + style
								+ "/lotteryError";
					}

				} else {// 不允许重复抽奖
					if (lotList != null && !lotList.isEmpty()) {
						notice = "亲,对不起,您今天已经参与过抽奖活动了，感谢您的参与，明天继续，本次不扣除您的积分.";
						// this.saveLotteryLog(member, null,user);
						model.addAttribute("notice", notice);

						return "modules/member/themes/" + style
								+ "/lotteryError";
					}

				}

				// 看是否有未消费的奖品如果有则不允许再抽取
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("userId", id);
				params.put("memberId", member.getId() + "");
				List myLtyLst = wechatDaoHelper
						.queryMineLotteryRecordByMember(params);
				if (myLtyLst != null && !myLtyLst.isEmpty()) {

					// queryMineLottery(member);
					// return null;

					notice = "亲,对不起,您还有" + myLtyLst.size()
							+ "个奖品未使用，暂时无法参与本次抽奖,请在我的奖品页面，查看自己获得奖品。谢谢！";
					// this.saveLotteryLog(member, null,user);
					model.addAttribute("notice", notice);

					return "modules/member/themes/" + style + "/lotteryError";
				}

				// 判断积分是否充足
				if (member.getActiveScore() < config.getCostScore()) {
					notice = "亲,对不起,你当前的积分不足,每次抽奖最低需要" + config.getCostScore()/1000
							+ "积分,谢谢您的参与,试试签到获得积分吧!";
					model.addAttribute("notice", notice);

					return "modules/member/themes/" + style + "/lotteryError";
				}

				List<Lottery> lotteryList1 = lotteryService
						.getUserLotteryByUserId(Long.parseLong(id));

				if (!(lotteryList1 != null && !lotteryList1.isEmpty())) {

					notice = "亲,对不起，抽奖活动还没有启动，请参与其它的活动吧!";
					model.addAttribute("notice", notice);

					return "modules/member/themes/" + style + "/lotteryError";
				}

				else {

					model.addAttribute("lotteryList", lotteryList1);

					if (AssertUtils.isNull(config.getRepeatCount())) {
						config.setRepeatCount(1);
					} else {
						if (config.getRepeatCount() < 1) {
							config.setRepeatCount(1);
						}
					}

					model.addAttribute("count", config.getRepeatCount());

					model.addAttribute("mycount", lotList.size());

					return "modules/member/themes/" + style + "/guaguaka";
				}
			} else {

				notice = "您所在的商家暂无抽奖活动";
				model.addAttribute("notice", notice);

				return "modules/member/themes/" + style + "/lotteryError";
			}

		} else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	/**
	 * 抽奖 *
	 * 
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	//TODO 抽奖处理
	@RequestMapping(value = "doLottery")
	public void doLottery(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) throws IOException {
		String uid = request.getParameter("uid");

		String reply = "";
		String message = "";

		User user = new User();
		user.setId(Long.parseLong(uid));
		WechatMember wechatMember = this.isLogin(request, uid);
		LotteryConfig config = lotteryConfigService.getByUserId(Long.parseLong(uid));

		// 扣除积分
		wechatMember.setActiveScore(wechatMember.getActiveScore() - config.getCostScore());
		wechatMember.setScore(wechatMember.getScore() - config.getCostScore());
		wechatMemberService.save(wechatMember);
		ScoreUtils.addWechatMemberCostScore(wechatMember,
				config.getCostScore()/1000, "参与抽奖活动消费积分.");

		Lottery mylottery = null;
		List<Lottery> lotteryList = lotteryService.getUserLotteryByUserId(Long
				.parseLong(uid));
		if (lotteryList != null && !lotteryList.isEmpty()) {
			// 抽奖动作
			MemberUtils mUtils = new MemberUtils();
			Lottery lottery = mUtils.extractLottery(lotteryList, config);

			mylottery = lottery;
			if (lottery == null) {
				reply = "再接再励 ";
				message = "太可惜了竟然与奖品擦肩而过!";
				this.saveLotteryLog(wechatMember, null, user);

				Date date = new Date();
				date.setHours(0);
				date.setMinutes(0);
				date.setSeconds(0);

				List<LotteryLog> lotList = lotteryLogService
						.findByMemberIdAndDate(Long.parseLong(uid),
								wechatMember.getId(), date);

				JSONObject jsonObj = new JSONObject();

				jsonObj.put("lotteryName", reply);
				jsonObj.put("message", message);
				jsonObj.put("mycount", lotList.size());

				response.setContentType("application/json;charset=utf-8");
				response.getWriter().print(jsonObj.toString());
				response.getWriter().flush();
				response.getWriter().close();
			} else {

				LotteryRecord record = new LotteryRecord();
				record.setEndTime(DateUtils.getDelayDate(config.getValidDays()));
				record.setLottery(lottery);
				record.setMember(wechatMember);
				record.setName(lottery.getName());
				record.setSourceType(LotteryRecord.SOURCE_TYPE_ME);
				record.setStatus(LotteryRecord.STATUS_NORMAL);
				record.setUser(user);
				// 中奖记录
				lotteryRecordService.save(record);

				saveLotteryLog(wechatMember, lottery, user); // 中奖日志

				// 判断是否还有余下的该奖品
				String validDate = DateUtils.formatDate(
						(record.getEndTime() == null) ? new Date() : record
								.getEndTime(), "MM月dd日");
				message = "恭喜您，本次获得了[" + lottery.getName() + "]奖品,请于"
						+ validDate + "之前到店里凭二维码核销使用,过期作废.";
				if (lottery.getScore() != null && lottery.getScore() > 0) {
					ScoreUtils.addScore(wechatMember, lottery.getScore(),"0", "会员中奖");

					// 加完积分后直接核销
					if (record.getLottery() != null
							&& Lottery.YES.equals(record.getLottery()
									.getAutoClear())) {
						record.setStatus(LotteryRecord.STATUS_CLEAR);
						record.setUpdateTime(new Date());
						record.setRemarks("成功增了" + lottery.getScore()/1000d
								+ "个积分并由系统自动核销.");
						lotteryRecordService.save(record);
					}

					message = "恭喜您，本次获得了[" + lottery.getName() + "]奖品,您成功增了"
							+ lottery.getScore()/1000d + "个积分。";
				}
				String title = "恭喜您中奖了";
				String desc = reply;
				if (StringUtils.isNotEmpty(config.getQrcodeTitle())) {
					title = config.getQrcodeTitle();
				}
				if (StringUtils.isNotEmpty(config.getQrcodeDesc())) {
					desc = config.getQrcodeDesc();

				}

				Date date = new Date();
				date.setHours(0);
				date.setMinutes(0);
				date.setSeconds(0);

				List<LotteryLog> lotList = lotteryLogService
						.findByMemberIdAndDate(Long.parseLong(uid),
								wechatMember.getId(), date);

				reply = "恭喜您";

				JSONObject jsonObj = new JSONObject();

				jsonObj.put("lotteryName", reply);
				jsonObj.put("message", message);
				jsonObj.put("mycount", lotList.size());

				response.setContentType("application/json;charset=utf-8");
				response.getWriter().print(jsonObj.toString());
				response.getWriter().flush();
				response.getWriter().close();

			}

		}

		//

	}

	/**
	 * @author Jakemanse
	 * @time 2013-10-18 下午9:32:52
	 * @function <p>
	 *           保存抽奖日志
	 *           </p>
	 * @param member
	 * @param mylottery
	 */
	public void saveLotteryLog(WechatMember member, Lottery mylottery, User user) {
		LotteryLog lotteryLog = new LotteryLog();
		lotteryLog.setMember(member);
		lotteryLog.setName((mylottery == null) ? null : mylottery.getName());
		lotteryLog.setUser(user);
		lotteryLog.setStatus(LotteryLog.STATUS_NORMAL);
		lotteryLog.setRemarks("参与抽奖。");
		lotteryLogService.save(lotteryLog);
	}
	
	
	/**
	 * 无会员砸金蛋
	 *@author xiaoqian
	 * @param member
	 * @param mylottery
	 * @param user
	 * 2014-10-17上午7:30:08
	 */
	public void saveLotteryLogByNotMeb(WechatMember member, Lottery mylottery, User user,Integer type) {
		LotteryLog lotteryLog = new LotteryLog();
		lotteryLog.setMember(member);
		lotteryLog.setName((mylottery == null) ? null : mylottery.getName());
		lotteryLog.setUser(user);
		lotteryLog.setType(type);
		lotteryLog.setStatus(LotteryLog.STATUS_NORMAL);
		lotteryLog.setRemarks("参与抽奖。");
		lotteryLogService.save(lotteryLog);
	}

	// 0-------抽奖--------

	/**
	 * 登陆后判断登陆前页面并调用该方法
	 * 
	 * @throws ParseException
	 * @throws IOException
	 */
	public String tofangfa(Long uid, Model model, HttpServletRequest request,
			HttpServletResponse response, String topage, String style,
			RedirectAttributes redirectAttributes) throws IOException,
			ParseException {

		String whichpage = "";

		if (topage.equals("tosignup")) {
			whichpage = this.toSignup(model, request, response);
			return whichpage;
		}

		if (topage.equals("toExchangeScore")) {
			whichpage = this.toExchangeScore(model, request, response);
			return whichpage;
		}
		if (topage.equals("seckillist")) {
			whichpage = this.seckillist(request, response, model,
					redirectAttributes);
			return whichpage;
		}
		if (topage.equals("findCoupon")) {
			whichpage = this.findCoupon(request, response, model,
					redirectAttributes);
			return whichpage;
		}
		if (topage.equals("guaguaka")) {
			whichpage = this.guaguaka(request, response, model,
					redirectAttributes);
			return whichpage;
		}

		if (topage.equals("mycommend")) {
			whichpage = this.mycommend(request, response, model,
					redirectAttributes);
			return whichpage;
		}

		if (topage.equals("toupdatePwd")) {
			whichpage = this.toupdatePwd(request, response, model,
					redirectAttributes);
			return whichpage;
		}
		if (topage.equals("myActivity")) {
			whichpage = this.myActivity(request, response, model,
					redirectAttributes);
			return whichpage;
		}
		if (topage.equals("myConsume")) {
			whichpage = this.myConsume(request, response, model,
					redirectAttributes);
			return whichpage;
		}
		if (topage.equals("myGoods")) {
			whichpage = this.myGoods(request, response, model,
					redirectAttributes);
			return whichpage;
		}
		if (topage.equals("recharge")) {
			whichpage = this.recharge(request, response, model,
					redirectAttributes);
			return whichpage;
		}
		
		if (topage.equals("eggsLottery")) {
			whichpage = this.toEggsLotteryPage(request, response, model,
					redirectAttributes);
			return whichpage;
		}

		if (topage.equals("doUpdatePersonInformation")) {
			whichpage = this.doUpdatePersonInformation(request, response,
					model, redirectAttributes);
			return whichpage;
		}

		else {
			whichpage = this.toIndex(request, response, model);
			return whichpage;

		}

	}

	/**
	 * 跳到登陆页面前根据 uid 和 wechatID 查询 会员。 如果有， 返回 手机号
	 */
	public Map<String, Object> beforeLogin(String uid, String wechatId) {
		Map<String, Object> map = new HashMap<String, Object>();
		String mobile = "";
		String pwd = "";

		User user = new User();

		user.setId(Long.parseLong(uid));

		WechatMember wechatMember = wechatMemberService.getByWechatMemberId(
				user, wechatId);

		if (AssertUtils.notNull(wechatMember)) {

			mobile = wechatMember.getMobile();

			// 是否需要初始化密码
			if (StringUtils.isEmpty(wechatMember.getPassword())
					|| wechatMember.isRandomPassword()) {
				pwd = com.thinkgem.jeesite.common.utils.StringUtils
						.getRandPassword();
				String enpwd = EncryptUtils.MD5EncodeString(pwd);
				wechatMember.setPassword(enpwd);
				wechatMember.setIsRandomPassword(true);

				wechatMemberService.save(wechatMember);
			}

			if (AssertUtils.isNullOrEmpty(pwd)) {
				pwd = null;
			}

			map.put("mobile", mobile);
			map.put("pwd", pwd);
		}

		return map;
	}

	// 修改密码
	//TODO 修改密码

	@RequestMapping(value = "toupdatePwd")
	public String toupdatePwd(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		String wechatId = request.getParameter("wechatId"); // OpenId

		style = this.isStyle(new User(Long.parseLong(id)));
		
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "toupdatePwd");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			Boolean isRandomPassword = false;
			
			if(member.getPassword()==null){
				
				isRandomPassword = true;
			}
			
			
			if(isRandomPassword){
				Map<String, Object> map = this.beforeLogin(id, wechatId);

				model.addAttribute("login_mobile", map.get("mobile"));
				model.addAttribute("pwd", map.get("pwd"));
			}

			request.setAttribute("isRandomPassword", isRandomPassword);

			return "modules/member/themes/" + style + "/updatePassword";
		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}
	//TODO 修改密码处理
	@RequestMapping(value = "updatePwd")
	public String updatePwd(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.parseLong(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "updatePwd");
		// oldpwd 原密码
		// password 新密码

		String oldpwd = request.getParameter("oldpwd");
		String password = request.getParameter("password");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			Boolean isRandomPassword = false;

			isRandomPassword = member.isRandomPassword();

			if (isRandomPassword == true) {

				member.setPassword(EncryptUtils.MD5EncodeString(password));
				member.setIsRandomPassword(false);
				wechatMemberService.save(member);

				WechatMember wechatMember = this.isLogin(request, id);

				request.setAttribute("wechatMember", wechatMember);

				request.setAttribute("message", "您的密码修改成功");
				
				return "modules/member/themes/" + style + "/memberCenter";

			}// 是随机密码
			else {
				Boolean pwdOk;
				pwdOk = EncryptUtils.validatePassword(oldpwd,
						member.getPassword());

				if (!pwdOk) {
					request.setAttribute("isRandomPassword", isRandomPassword);
					request.setAttribute("message", "原密码错误");

					return "modules/member/themes/" + style + "/updatePassword";
				} else {
					member.setPassword(EncryptUtils.MD5EncodeString(password));
					member.setIsRandomPassword(false);
					wechatMemberService.save(member);

					WechatMember wechatMember = this.isLogin(request, id);

					request.setAttribute("wechatMember", wechatMember);

					request.setAttribute("message", "您的密码修改成功");
					
					List<Map<String, Object>> myGoodsList = memberService
							.selectmyGoodsBymemberID(member.getId());
					
					model.addAttribute("goodsNumber", myGoodsList.size());
					
					return "modules/member/themes/" + style + "/memberCenter";

				}
			}// 不是随机密码

		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	/**
	 * @author Jakemanse
	 * @time 2014-3-26 上午9:06:26
	 * @function <p>
	 *           看广告获得积分
	 *           </p>
	 * @return
	 */
	//TODO 看广告获得积分
	@RequestMapping(value = "advtScore")
	public String advtScore(Long uid, String wid, Long pid, String topage,
			HttpServletRequest request, HttpServletResponse response,
			Model model, RedirectAttributes redirectAttributes) {
		
		

		String style = request.getParameter("style");
		style = this.isStyle(new User(uid));
		style = this.isStyle(style);
		String message = "";
		if (uid != null
				&& com.thinkgem.jeesite.common.utils.StringUtils
						.isNotEmpty(wid)) {
			User user = new User();
			user.setId(uid);
			WechatMember member = wechatMemberService.getByWechatMemberId(user,
					wid);
			if (member != null) {
				MemberScoreService memberScoreService = (MemberScoreService) SpringUtils
						.getBean("memberScoreService");
				int n = memberScoreService.queryTodayAdvScoreCount(member);
				CustomPageService customPageService = (CustomPageService) SpringUtils
						.getBean("customPageService");
				CustomPage page = customPageService.get(pid);

				if (n >= page.getRepeatCount() && n > 0) {
					message = "亲，对不起，您今天已经参与过" + n + "次该活动了,不能再参与了，谢谢！";
				} else {

					// 小于等于0 还没有获取今天的广告积分
					/*int score = (member.getActiveScore() == null) ? 0 : member.getActiveScore();
					member.setActiveScore(score+page.getScore());
					member.setScore(member.getScore() + page.getScore());
					wechatMemberService.save(member);*/
					// 日志
					ScoreUtils.addScore(member, page.getScore(),"0","看广告送"+((double)page.getScore())/1000+"个活动积分");
					message = "恭喜您本次获得了" + ((double)page.getScore())/1000 + "个积分!";
				}

			} else {
				message = "亲，对不起，您还不是我们的会员，请先注册成会员再参与我们的活动吧，谢谢！";
			}

		} else {
			message = "亲，对不起，您提交的是非法数据请求，我们无法识别您的会员信息，请先注册成会员再参与我们的活动吧，谢谢！";
		}

		model.addAttribute("message", message);

		return "modules/member/themes/" + style + "/signupOk";
	}

	// --------我的物品---------------------
	//TODO 我的物品
	@RequestMapping(value = "myGoods")
	public String myGoods(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) throws IOException,
			ParseException {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "myGoods");

		WechatMember member = this.isLogin(request, id);
		if (AssertUtils.isNull(member)) {
			String url = getOAuthUrl("/member/myGoods?a=1",id,request,response);
			return "redirect:"+url;
		}
		if (AssertUtils.notNull(member)) {

			Long mid = member.getId();
			List<Map<String, Object>> myGoodsList = memberService
					.selectmyGoodsBymemberID(mid);
			
			
			if (AssertUtils.notNull(myGoodsList)) {
				if (myGoodsList.size()<1) {
					myGoodsList = null;
				}
			}

//			if (AssertUtils.notNull(myGoodsList)) {
//				if (myGoodsList.size() < 1) {
//					myGoodsList = null;
//				} else {
//					
//				
//					for (int i = 0; i < myGoodsList.size(); i++) {
//
//						if (AssertUtils.notNull(myGoodsList.get(i).get(
//								"end_time"))) {
//						
//							myGoodsList.get(i).put("end_time", Integer.parseInt(myGoodsList.get(i).get("end_time")+""));
//						}
//					}
//
//				}
//			}

			model.addAttribute("myGoodsList", myGoodsList);

			return "modules/member/themes/" + style + "/myGoods";
		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");

			return "modules/member/themes/" + style + "/reg";
		}

	}
	//TODO 删除我的物品
	@RequestMapping(value = "deleteMyGoods")
	public String deleteMyGoods(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) throws IOException,
			ParseException {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId
		String del_id = request.getParameter("delID");

		String type = request.getParameter("type");

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "myGoods");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			memberService.deleteMyGoods(Long.parseLong(del_id), type);

			return this.myGoods(request, response, model, redirectAttributes);
		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	// --------我的消费---------------------
	//TODO 我的消费
	@RequestMapping(value = "myConsume")
	public String myConsume(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "myConsume");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			Long mid = member.getId();
			List<Map<String, Object>> myConsumeList = memberService
					.selectmyConsumeBymemberID(mid);

			if (AssertUtils.notNull(myConsumeList)) {
				if (myConsumeList.size() < 1) {
					myConsumeList = null;
				}
			}

			model.addAttribute("myConsumeList", myConsumeList);

			return "modules/member/themes/" + style + "/myConsume";
		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}
	//TODO 活动中心
	@RequestMapping(value = "myActivity")
	public String myActivity(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "myActivity");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			request.setAttribute("wechatMember", member);
			return "modules/member/themes/" + style + "/wechatMember";
		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");

			return "modules/member/themes/" + style + "/reg";
		}

	}
	//TODO 我的充值
	@RequestMapping(value = "recharge")
	public String recharge(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "myActivity");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			request.setAttribute("wechatMember", member);
			return "modules/member/themes/" + style + "/recharge";
		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");

			return "modules/member/themes/" + style + "/reg";
		}

	}
	//TODO 注册登陆
	@RequestMapping(value = "regLogin")
	public String regLogin(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes)
			throws NumberFormatException, IOException, ParseException {

		String style = request.getParameter("style");


		String uid = request.getParameter("uid");
		style = this.isStyle(new User(Long.valueOf(uid)));
		String wechatId = request.getParameter("wechatId");

		String topage = request.getParameter("topage");
		String page = "";

		String mobile = request.getParameter("mobile");
		String pwd = request.getParameter("pwd");

		request.setAttribute("topage", topage);
		request.setAttribute("wechatId", wechatId);
		request.setAttribute("uid", uid);
		request.setAttribute("style", style);

		// 判断是否已经登录
		boolean login = false;

		User user = new User();
		user.setId(Long.parseLong(uid));

		WechatMember member = wechatMemberService.getByWechatMemberId(user,
				wechatId);
		WechatMember wechatMember = wechatMemberService.getByMobile(user,
				mobile);

		if (member != null && wechatMember != null) {
			if (member.getMobile().equals(wechatMember.getMobile())) {
				login = true;
				member.setPassword(EncryptUtils.MD5EncodeString(pwd));
				member.setIsRandomPassword(false);
				wechatMemberService.save(member);
			}
			// /登录
			if (login) {
				SessionMemberUtils.addSessionValue(request, "member_" + uid,
						member);
			}
		} else {
			login = false;
		}

		model.addAttribute("wechatMember", member);

		if (login) {
			// TODO 跳转成功后可以通过topage调回原来的
			request.setAttribute("wechatMember", member);
			
			List<Map<String, Object>> myGoodsList = memberService
					.selectmyGoodsBymemberID(member.getId());
			
			model.addAttribute("goodsNumber", myGoodsList.size());
			
			return "modules/member/themes/" + style + "/memberCenter";

		}

		else {

			return "modules/member/themes/" + style + "/regLogin";

		}

	}

	// ----修改个人资料
	//TODO 修改个人资料
	@RequestMapping(value = "doUpdatePersonInformation")
	public String doUpdatePersonInformation(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "doUpdatePersonInformation");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			request.setAttribute("wechatMember", member);
			return "modules/member/themes/" + style
					+ "/updatePersonInformation";
		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));

			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	// ----修改个人资料
	//TODO 修改个人资料处理
	@RequestMapping(value = "updatePersonInformation")
	public String updatePersonInformation(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		String sex = request.getParameter("sex");
		String birthday = request.getParameter("birthday");
		String mobile = request.getParameter("mobile");
		String name = request.getParameter("name");
		String mid = request.getParameter("mid");
		String IDCardNumber = request.getParameter("IDCardNumber");
		String email = request.getParameter("email");

		System.out.println("sex" + sex);

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "dopayPassword");

		WechatMember member = this.isLogin(request, id);
		if (AssertUtils.notNull(member)) {
			Map<String, Object> map = new HashMap<String, Object>();
			// map.put("id", mid);
			// map.put("name", name);
			// map.put("sex", sex);
			// map.put("birthday", birthday);
			//
			//
			// memberService.updateMemberInformation(map);
			/*
			if(StringUtils.isNotEmpty(mobile)){
				if(StringUtils.isEmpty(member.getMobile())){
					member.setName(name);
					member.setSex(sex);
					member.setBirthday(birthday);
					member.setMobile(mobile);
					wechatMemberService.save(member);
					ScoreUtils.addScore(member, 1000,"0","注册会员送积分");
				}
			}
			*/
			if(StringUtils.isNotEmpty(mobile)){
				if(StringUtils.isEmpty(member.getMobile())){
					ScoreUtils.addScore(member, 1000, "1","完善个人资料，送1个消费积分");
				}
			}
			
			member.setName(name);
			member.setSex(sex);
			member.setBirthday(birthday);
			member.setMobile(mobile);
			
			member.setIDCardNumber(IDCardNumber);
			member.setEmail(email);
			
			wechatMemberService.save(member);

			model.addAttribute("message", "您的用户信息修改成功！！！");

			model.addAttribute("wechatMember", member);

			this.updateMemberSession(request, id, member);

			return "modules/member/themes/" + style + "/memberCenter";
		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));

			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	// 更新session中用户信息
	public void updateMemberSession(HttpServletRequest request, String uid,
			WechatMember member) {
		SessionMemberUtils.addSessionValue(request, "member_" + uid, member);
	}

	// ----跳到设置支付密码页面
	//TODO 设置支付密码

	@RequestMapping(value = "dopayPassword")
	public String dopayPassword(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "dopayPassword");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			return "modules/member/themes/" + style + "/payPassword";
		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");

			return "modules/member/themes/" + style + "/reg";
		}

	}

	// ----设置支付密码
	//TODO 设置支付密码处理
	@RequestMapping(value = "payPassword")
	public String payPassword(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");


		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		String password = request.getParameter("password");

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "doUpdatePersonInformation");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			member.setPayPassword(EncryptUtils.MD5EncodeString(password));

			wechatMemberService.save(member);

			model.addAttribute("message", "您的支付密码设置成功");

			model.addAttribute("wechatMember", member);

			this.updateMemberSession(request, id, member);

			return "modules/member/themes/" + style + "/memberCenter";
		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));

			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	// 超链接传参查询用户是否存在

	/**
	 * @author songyan
	 * @time 2014-2-28
	 * @param uid
	 * @param wechatID
	 * @param mobile
	 * @return true 是会员
	 * @return false 不是会员
	 */
	@RequestMapping(value = "seletIsMember")
	public Boolean seletisMember(Long uid, Model model,
			HttpServletRequest request, HttpServletResponse response) {
		Boolean isMember = false;

		User user = new User();
		user.setId(uid);

		String wechatId = request.getParameter("wechatId");
		String id = request.getParameter("uid");
		
		
		if (AssertUtils.isNullOrEmpty(wechatId)
				|| AssertUtils.isNullOrEmpty(id)) {
			isMember = false;
			return isMember;
		}// wechatId 或 uid 有一个为空

		else {
			WechatMember wechatMember = wechatMemberService
					.getByWechatMemberId(user, wechatId);

			if (AssertUtils.notNull(wechatMember)) {
				isMember = true;
				return isMember;
			}// 查询会员不为空
			else {
				isMember = false;
				return isMember;
			}

		}

	}

	// 超链接传参查询用户是否存在

	// ----跳到修改我的密码页面
	//TODO 修改我的密码

	@RequestMapping(value = "doupdatepayPassword")
	public String doupdatepayPassword(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");
		

		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "doupdatepayPassword");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			return "modules/member/themes/" + style + "/updatePayPassword";
		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");
			return "modules/member/themes/" + style + "/reg";
		}

	}

	// ----修改我的密码
	//TODO 修改我的密码处理

	@RequestMapping(value = "updatepayPassword")
	public String updatepayPassword(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");

		style = this.isStyle(style);

		String id = request.getParameter("uid"); // userId
		style = this.isStyle(new User(Long.valueOf(id)));
		String wechatId = request.getParameter("wechatId"); // OpenId

		String oldpassword = request.getParameter("oldpassword");
		String password = request.getParameter("password");

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "doupdatepayPassword");

		WechatMember member = this.isLogin(request, id);

		if (AssertUtils.notNull(member)) {

			Boolean pwdOk;
			pwdOk = EncryptUtils.validatePassword(oldpassword,
					member.getPayPassword());

			if (!pwdOk) {
				request.setAttribute("message", "原密码错误");

				return "modules/member/themes/" + style + "/updatePayPassword";

			} else {
				member.setPayPassword(EncryptUtils.MD5EncodeString(password));

				wechatMemberService.save(member);

				model.addAttribute("message", "您的支付密码修改成功");

				model.addAttribute("wechatMember", member);

				this.updateMemberSession(request, id, member);

				return "modules/member/themes/" + style + "/memberCenter";
			}

		}

		else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));
			
			model.addAttribute("reg", "reg");

			return "modules/member/themes/" + style + "/reg";
		}

	}

	/**
	 * 跳到优惠券换的商品页
	 * 
	 * @author xiaoqian
	 * @param id
	 * @param model
	 * @param request
	 * @param response
	 * @return 2014-3-6下午3:39:55
	 */
	//TODO 跳到优惠券换的商品页
	@RequestMapping(value = "tocoponepro")
	public String tocoponepro(Model model, HttpServletRequest request,
			HttpServletResponse response) {

		String style = request.getParameter("style");


		String wechatId = request.getParameter("wechatId"); // OpenId
		String coponId = request.getParameter("coponId"); // OpenId

		String uid = request.getParameter("uid");
		style = this.isStyle(new User(Long.valueOf(uid)));

		Long id = Long.parseLong(uid);

		User user = new User();
		user.setId(id);

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);

		model.addAttribute("topage", "findCoupon");

		// 兑换的列表

		CouponConfig couponConfig = couponConfigService.get(Long
				.parseLong(coponId));

		request.setAttribute("couponConfig", couponConfig);

		return "modules/member/themes/" + style + "/couponproductShow";
	}
	
	
	public WechatMember registerMember(User user,String mobile,String wechatId,Long uid,HttpServletRequest request){
			WechatMember wechatMember = new WechatMember();
			wechatMember.setUser(user);
			wechatMember.setWechatId(wechatId);
			wechatMember.setScore(0);
			wechatMember.setActiveScore(0);
			wechatMember.setConsumeScore(0);
			wechatMember.setCreditScore(0);
			wechatMember.setName("");
			// wechatMember.setBirthday(birthday);
			wechatMember.setSex("保密");
			wechatMember.setMobile(mobile);
			// wechatMember
			// .setPassword(EncryptUtils.MD5EncodeString(password));
			wechatMember.setLastSignTime(null);
			wechatMember.setIsRandomPassword(false);

			Boolean advanceInterface = memberService.selectInterfaceFlagByuserID(uid);	//是否开通了高级接口

			if (advanceInterface) {
				try {
					WechatMember member = memberService.operateInterface(
							uid, wechatId);
					wechatMember.setCity(member.getCity());
					wechatMember.setCountry(member.getCountry());
					wechatMember.setHeadimgurl(member.getHeadimgurl());
					wechatMember.setLanguage(member.getLanguage());
					wechatMember.setNickname(member.getNickname());
					wechatMember.setProvince(member.getProvince());
					// wechatMember.setSex(member.getSex());
					wechatMember
							.setSubscribeTime(member.getSubscribeTime());
					wechatMember.setAge(member.getAge());
				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			if(wechatMember.getId()==null || wechatMember.getId() <= 0)	  
				wechatMemberService.save(wechatMember);
			// 生成推荐码  暗号
			wechatMember
					.setRecommendCode(""
							+ StringUtils.leftPad(
									"" + wechatMember.getId(), 6, "0"));// 推荐码

			//生成会员卡号
			wechatMember.setNumber("MBR"
					+ StringUtils.leftPad("" + wechatMember.getId(), 10,
							"0")); // 会员卡号

			wechatMemberService.save(wechatMember);
			// 把会员表推荐码字段置成会员ID 推荐码=会员ID
			// 生成会员卡
			generateMemberCard(wechatMember, request);
			return wechatMember;

	}
}
